Return 类型,'FutureOr<Database>',是 Flutter 中潜在的不可空类型

Return type, 'FutureOr<Database>', is a potentially non-nullable type in Flutter

我正在使用 Flutter 并尝试创建一个数据库并使用 bloc 进行状态管理,如下面的代码所示:

 late Database database;
  List<Map> tasks = [];

  Future<void> createDatabase() async {
    database =
        await openDatabase('todo.db', version: 1, onCreate: (database, version) {
      debugPrint('Database created');
      database
          .execute(
              'CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, date TEXT, time TEXT, status TEXT, CONSTRAINT task_unique UNIQUE (title, date, time))')
          .then((value) {
        debugPrint('Table created');
      }).catchError((error) {
        debugPrint('Error when creating table ${error.toString()}');
      });
    }, onOpen: (database) {
      getDataFromDatabase(database).then((value) {
        tasks = value;
        emit(AppGetDatabaseState());
      });
      debugPrint('Database opened');
    }).then((value) {
      database = value;
      emit(AppCreateDatabaseState());
    });
  }

问题是我收到一个错误:

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<Database>', is a potentially non-nullable type.

错误出现在代码末尾这一行:

.then((value) {
  database = value;
  emit(AppCreateDatabaseState());
});

整个代码看起来很乱,我是这样解释的:

//Here, we define a constant string, the query that we will execute when creating the database (We want a good looking code)
const String createDatabaseQuery =
    'CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, date TEXT, time TEXT, status TEXT, CONSTRAINT task_unique UNIQUE (title, date, time))';

//Probably, when the function will finish you will use the database variable, remember to await the createDatabase function before using it, as it will wait that the function finishes.
Future<void> createDatabase() async {
  //We don't want all those .then! With a great probability, if you use it, you're doing something wrong.
  database = await openDatabase(
    'todo.db',
    version: 1,
    onCreate: (database, version) async {
      try {
        //If the future completes successfully, so there isn't any error
        await database.execute(createDatabaseQuery);
        debugPrint("Database created successfully");
      } catch (error) {
        debugPrint('Error when creating table ${error.toString()}');
      }
    },
    onOpen: (database) async {
      var data = await getDataFromDatabase(database);
      tasks = data;
      emit(AppGetDatabaseState());

      debugPrint('Database opened');
    },
  );
  emit(AppCreateDatabaseState());
}

代码现在好多了对吧? 如果我理解您要实现的目标:

您正在尝试执行 openDatabase(...).then(assignDatabaseVar)

但你也期待着未来,所以 dart 会把它看成

执行函数,执行然后阻塞,等待然后阻塞

但是“然后”returns无效(所以无效)

而且您不能等待空值,只能等待 Future 或 FutureOr。

希望我说清楚了,如果有效请通知我!