如何解决Flutter中“ getter'length'被调用为null的错误”

问题描述 投票:0回答:2

我正在尝试显示我的工作清单,但它一直失败,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),
                      ),
                    ),

enter image description here

flutter dart visual-studio-code
2个回答
0
投票

使用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...

0
投票

请执行步骤1和2步骤1:删除此行checkList = CheckList.browse();来自initState()第2步:将future:checkList更改为future:Browse()

如果需要进一步澄清,请参考步骤3和4第3步:检查路径数据/ checklist.json步骤4:检查解析,我没有CheckList类,无法模仿

© www.soinside.com 2019 - 2024. All rights reserved.