异步函数返回null

时间:2020-02-07 06:10:54

标签: asynchronous flutter dart

dayManager.getDay()返回null而不是Map

@override
void initState() {
    super.initState();
    print("init");
    getDay();
  }

  void getDay() async {
    Future<Map<int, int>> dayExistingValueMap = dayManager.getDay();
    dayExistingValueMap.then((map) {
      print('dayExisting ____ $map');
    });
  }

但是当我在返回之前打印出它时,地图包含所有值。

    Future<Map<int, int>> getDay() async {
    final Future<Database> dbFuture = databaseHelper.initializeDatabase();
    dbFuture.then((database) async {
      final bool checkIfExists = await databaseHelper.checkIfExist(day.dateStr);
      if (checkIfExists) {
        Day dbDay = await databaseHelper.getDaySingle(day.dateStr);
        print('_${dbDay.valueMap}');
        return dbDay.valueMap;
      } else {
        return this.day.valueMap;
      }
    });
  }

3 个答案:

答案 0 :(得分:0)

您的函数返回的是null,因为您实际上并未返回任何东西。您需要返回dbFuture.then的结果,如下所示:

    Future<Map<int, int>> getDay() async {
      final Future<Database> dbFuture = databaseHelper.initializeDatabase();
      return dbFuture.then((database) async {
        final bool checkIfExists = await databaseHelper.checkIfExist(day.dateStr);
        if (checkIfExists) {
          Day dbDay = await databaseHelper.getDaySingle(day.dateStr);
          print('_${dbDay.valueMap}');
          return dbDay.valueMap;
        } else {
          return this.day.valueMap;
        }
      });
    }

Future.then返回一个Future,该{完成后返回到提供的闭包的返回值。

答案 1 :(得分:0)

我们可以使用return dbFuture.then((database) async {代替final Database dbFuture = await databaseHelper.initializeDatabase();

Future<Map<int, int>> getDay() async {
    final Database dbFuture = await databaseHelper.initializeDatabase();

      final bool checkIfExists = await databaseHelper.checkIfExist(day.dateStr);
      if (checkIfExists) {
        Day dbDay = await databaseHelper.getDaySingle(day.dateStr);
        print('_${dbDay.valueMap}');
        return dbDay.valueMap;
      } else {
        return this.day.valueMap;
      }

  }

答案 2 :(得分:0)

您正在返回then内的闭包内的值,因此就getDay方法而言,您没有返回任何值。我的建议是完全不要使用then,因为它会直接引起这类混乱。 (更不用说调用then了,将您的方法标记为async的目的是可以使用await的目的。)

Future<Map<int, int>> getDay() async {
  final database = await databaseHelper.initializeDatabase();
  final bool checkIfExists = await databaseHelper.checkIfExist(day.dateStr);
  if (checkIfExists) {
    Day dbDay = await databaseHelper.getDaySingle(day.dateStr);
    print('_${dbDay.valueMap}');
    return dbDay.valueMap;
  } else {
    return this.day.valueMap;
  }
}