FlutterDart空值检查运算符用于空值错误

mmvthczy  于 2022-12-05  发布在  Flutter
关注(0)|答案(3)|浏览(141)

我想做一个待办事项列表应用程序。我在我的项目中使用Sqflite。

小工具

`

return FutureBuilder(
    future: databaseTrans.getTables(),
    builder: (context, snapshot) {
      if (snapshot.data == null) {
        return taskBookErrorWidget(context);
      } else {
        return GridView.count(
          crossAxisCount: 3,
          children: List.generate(snapshot.data!.length, (i) {
                return InkWell(
                  onTap: () {},
                  child: Container(
                    width: 300,
                    height: 300,
                    margin: EdgeInsets.all(10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Text(
                        snapshot.data![i].name.toString(),
                        style: TextStyle(color: Colors.white)),
                  ),
                );
          }),
        );
      }
    },
  );
}

`

个错误

`

The following _CastError was thrown building FutureBuilder<List<taskBooksDataModel>>(state: _FutureBuilderState<List<taskBooksDataModel>>#da7bd):
Null check operator used on a null value

The relevant error-causing widget was: 
  FutureBuilder<List<taskBooksDataModel>> FutureBuilder:file:///C:/Users/Administrator/Desktop/todolist/lib/screens/taskBooksScreen/taskBookWidget.dart:16:12
When the exception was thrown, this was the stack: 
#0      _SnackBarState.initState (package:flutter/src/material/snack_bar.dart:391:21)
#1      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5015:57)
#2      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
#3      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#4      Element.updateChild (package:flutter/src/widgets/framework.dart:3586:20)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4904:16)

`

数据库函数

`

Future<List<taskBooksDataModel>> getTables() async {
    Database db = await database;

    var result = await db.query("sqlite_master");
    return taskBooksDataModel.convertToTaskBookDataModel(result);
  }

`
我应该怎么做?我想从表中读取数据,并将它们写入FutureBuilder上的Text()。我有两个表。其中一个包含任务书的名称。

xyhw6mcr

xyhw6mcr1#

请尝试先检查ConnectionState,然后检查快照数据。

if (snapshot.connectionState == ConnectionState.waiting){
        return CircularProgressIndicator();

}
6ojccjat

6ojccjat2#

这基本上意味着您在变量为null的地方使用了'!'。检查一下您的API是否返回了null。还可以查看一下docs,了解如何检查快照是否有数据

kkbh8khc

kkbh8khc3#

示例中的代码说snapshot.data![i].name.toString()中的data永远不会是null,但在执行过程中有时会变成null。添加一些条件,以便在文本小部件中正确处理输入数据。例如:

Text(
    snapshot.data != null
        ? snapshot.data![i].name.toString()
        : '',
        style: TextStyle(color: Colors.white),
    ),
),

相关问题