0

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>

2 Answers2

1

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;
}
Riwen
  • 4,734
  • 2
  • 19
  • 31
  • I want checkId to doesn't be of type Future but only bool. – federico D'Armini Feb 20 '21 at 17:49
  • You could use [`waitFor`](https://api.dart.dev/stable/2.3.1/dart-cli/waitFor.html), but it is experimental and not recommended to use, at all. There is really no reason to not use async, anyway. – Riwen Feb 20 '21 at 19:50
  • Take a look at this please : https://stackoverflow.com/questions/66297035/call-async-function-inside-textformfield-validator-flutter – federico D'Armini Feb 20 '21 at 22:07
0

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;
}
Victor Eronmosele
  • 7,040
  • 2
  • 10
  • 33