federico D'Armini
federico D'Armini

Reputation: 321

Future still returns null Flutter

I have this function that calls a Future<bool> function :

bool checkId(String id, context) {
  bool ret;
  checkMissingId(id, context).then((value) => ret = value);
  return ret;

That calls :

Future<bool> checkMissingId(String id, context) async {
  String str = id.toLowerCase();
  String letter = str[0];
  if (checkStr(id, letter, str) == false)
    return false; //checks some rules on strings
  else {
    try {
      var data = await FirebaseFirestore.instance
          .collection("ids/tabs/" + letter)
          .doc(str)
          .get();
      if (data.exists) {
        return false;
      } else
        return true;
    } catch (e) {
      await showErrDialog(context, e.code);
      return false;
    }
  }
}

ret returns null, not a bool value.

Edit : checkId must be of type bool, not Future<bool>

Upvotes: 0

Views: 142

Answers (2)

Riwen
Riwen

Reputation: 5200

Because it is null when the checkId function returns. You should await the operation, like this:

Future<bool> checkId(String id, context) async {
  bool ret = await checkMissingId(id, context);
  return ret;
}

Upvotes: 1

Victor Eronmosele
Victor Eronmosele

Reputation: 7716

You need to pause the execution of the program for the checkMissingId method to complete before return the ret variable. You do this by using the await keyword and marking the function as async.

You should change the code to:

Future<bool> checkId(String id, context) async {
  bool ret = await checkMissingId(id, context);
  return ret;
}

Upvotes: 0

Related Questions