The dayManager.getDay() returns a null instead of a 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');
    });
  }

but when I print it out beforee returning it, the Map contains all the values.

    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;
      }
    });
  }


Solution 1: Ben Konyi

Your function is returning null since you're not actually returning anything. You need to return the result of dbFuture.then, like so:

    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 returns a Future that completes to the return value of the closure provided.


Solution 2: Dev

Instead of return dbFuture.then((database) async { we can use 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;
      }

  }


Solution 3: Abion47

You are returning the value within the closure inside the then, so as far as the getDay method is concerned, you aren't returning anything. My recommendation is to not use then at all, since it directly causes these kinds of confusions. (Not to mention calling then defeats the purpose of marking your method as async which is to be able to use 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;
  }
}