我在另一個目錄中創建了一個串列,它是一個 JSON 資料串列,我已經在螢屏上顯示了它,還添加了一個用作搜索欄的 TextField。如果我搜索串列中的一個字母(或字母組合),它可以正常作業,但是當我搜索串列之外的內容時,除了 Appbar 之外,整個頁面都變為空白。這是我的代碼:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List _items = [];
List _itemsForDisplay = [];
// Fetch content from the json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/Symptoms.json');
final data = await json.decode(response);
setState(() {
_items = data["Symptoms"];
_itemsForDisplay = _items;
});
}
@override
void initState() {
// TODO: implement initState
readJson();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Diagnose',
),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
// Display the data loaded from sample.json
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return index == 0 ? _searchBar() : _ListItem(index);
},
itemCount: _itemsForDisplay.length,
),
)
],
),
),
);
}
_searchBar() {
return Padding(
padding: const EdgeInsets.all(8),
child: TextField(
decoration: InputDecoration(hintText: 'Search'),
onChanged: (text) {
text = text.toLowerCase();
setState(() {
_itemsForDisplay = _items.where((item) {
var itemTitle = item.toLowerCase();
return itemTitle.contains(text);
}).toList();
});
},
),
);
}
_ListItem(index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_itemsForDisplay[index]),
),
);
}
}
這是在搜索我串列中的物體之前的圖片

當我搜索“。”時會發生這種情況。或不在我串列中的任何內容:

uj5u.com熱心網友回復:
在您的專案生成器中僅回傳_ListItem(index)并放在_searchBar擴展之外。在當前代碼中,您正在跳過串列中的第一個元素并顯示搜索欄,這是錯誤的。這就是為什么當串列長度為 0 時你什么都看不到。因為 builder 沒有被執行。
因此,您構建的方法應如下所示:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Diagnose',
),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
// Display the data loaded from sample.json
_searchBar(),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return _ListItem(index);
},
itemCount: _itemsForDisplay.length,
),
)
],
),
),
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495061.html
