我正在尝试显示我的工作清单,但它一直失败,snapshot.data似乎为空。请如何解决此问题
static Future<List<CheckList>> browse() async {
String content = await rootBundle.loadString('data/checklist.json');
await Future.delayed(Duration(seconds: 1));
List collection = json.decode(content);
List<CheckList> _checklist =
collection.map((json) => CheckList.fromJson(json)).toList();
return _checklist;
}
Future<List<CheckList>> checkList;
@override
void initState() {
super.initState();
checkList = CheckList.browse();
}
body: FutureBuilder(
future: checkList, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
// if (snapshot.hasError) return Text('Error is: ${snapshot.error}');
var checkList = snapshot.data;
return ListView.separated(
itemCount: checkList.length,
itemBuilder: (BuildContext context, int index) {
CheckList checklist = checkList[index];
return ListTile(
title: Padding(
padding: const EdgeInsets.fromLTRB(0, 15, 0, 0),
child: Text(
checklist.checkListName,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
使用snapshot
时,应始终检查FutureBuilder
是否有数据。有snapshot.hasData
属性可以为您提供帮助。
if (snapshot.hasData) {
return Container(...); // do what you want or validate snapshot.data If unexpceted.
} else if (snapshot.hasError) {
return Container(...); // show empty, snackbar, or something useful error message ui.
}
return Container(...); // show loading... ex. CircularProgressIndicator...
请执行步骤1和2步骤1:删除此行checkList = CheckList.browse();来自initState()第2步:将future:checkList更改为future:Browse()
如果需要进一步澄清,请参考步骤3和4第3步:检查路径数据/ checklist.json步骤4:检查解析,我没有CheckList类,无法模仿