fed9115
fed9115

Reputation: 105

Flutter getting bool out of Future<bool> but got null assigned to the Boolean variable

I am getting an error when I try to get the boolean result out of the Future<bool> in Flutter. The scenario is, I am trying to query in the Firebase Firestore associated with my project, and check if the query contains no item. Therefore, I use this snippet to do this query and return it as a Future<bool>:

static Future<bool> checkDupTitle (String uid, String title) {
    return FirebaseFirestore.instance
          .collection(DBCollection.summits.toString())
          .where(SummitWhirlwindModel.UID, isEqualTo: uid)
          .where(SummitWhirlwindModel.TITLE, isEqualTo: title)
          .snapshots().isEmpty;
}

To get the boolean result out of the Future<bool>, I have tried both async/await and .then syntax. Unfortunately, neither of them works. For example, when I use .then, I get the boolean value of containsDup assigned to null, below is the function call:

bool isValid(String uID) {
    Future<bool> containsDupFuture = checkDupTitle(uID, this.title.value);
    bool containsDup;
    containsDupFuture.then((value) => containsDup = value);
    return !containsDup;
}

Can anyone help me with this problem? I am new to flutter and when I look up the related questions on Stackoverflow, I am not able to get any valuable answers to my case. Thank you so much for answering this question ahead!!!

Upvotes: 0

Views: 631

Answers (1)

Mohamed Amin
Mohamed Amin

Reputation: 1067

Try this:

  static Future<bool> checkDupTitle (String uid, String title) {
    return FirebaseFirestore.instance
        .collection(DBCollection.summits.toString())
        .where(SummitWhirlwindModel.UID, isEqualTo: uid)
        .where(SummitWhirlwindModel.TITLE, isEqualTo: title)
        .get().then((QuerySnapshot snapshot){
          if(snapshot.docs.length >0){
            return true;
          }else{
            return false;
          }
    });
  }

Be sure to initialize the function:

@override
void initState()   {
checkDupTitle (String uid, String title);  //provide uid,title
                     }

Upvotes: 1

Related Questions