Flutter : Conditions must have a static type of 'bool'

I'm trying to learn firebase with flutter and i ran into this problem here is my code :

 FirebaseFirestore.instance
            .collection('attendees')
            .doc(user.uid)
            .snapshots()
            .listen((snapshot) {
          if (snapshot.data() != null) {
            if (snapshot.data()!['attending']) {
              _attending = Attending.yes;
            } else {
              _attending = Attending.no;
            }
          } else {
            _attending = Attending.unknown;
          }
          notifyListeners();
        });

what is the solution ? the exact problem is within this line : if (snapshot.data()!['attending']) {

how can I rewrite this so i wont ruin the current functionality ? I appreciate your help inadvance

2 answers

  • answered 2021-06-23 07:17 Ashok Kuvaraja

    Just store the snapshot.data() to the local map variable and do the operations by that.

        _attendingSubscription = FirebaseFirestore.instance
            .collection('attendees')
            .doc(user.uid)
            .snapshots()
            .listen((snapshot) {
          final Map<String, dynamic>? data = snapshot.data();
          if (data != null) {
            _attending = data['attending'] ? Attending.yes : Attending.no;
          } else {
            _attending = Attending.unknown;
          }
          notifyListeners();
        });
    

  • answered 2021-06-23 07:58 anirudh

    The reason you are getting error -

    Conditions must have a static type of 'bool'

    because on line snapshot.data()!['attending'] an = sign is missing.

    To make your code work just do

    if (snapshot.data() != snapshot.data()!['attending']) {
                  _attending = Attending.yes;
                } else {
                  _attending = Attending.no;
                }
    

    Understanding The Error

    I would also like to point out that Dart a stricter language (more like Java in terms of 'truthy' values).

    In JavaScript you can use any ‘truthy’ value in a conditional statement. In Dart you cannot use ‘truthy’ values. For example:

    var name = 'Joe';
    if (name) {
      // do something...
    

    OR

    var a = 1
    if(a){
    //this would work in JavaScript
    }
    

    You cannot do such things in Java or Dart. The reason is that Dart requires that a condition is a bool true not just a 'truthy' value. You could correct the code by changing it to:

    if (name.isNotEmpty)
    

    OR

    if(a==1)
    {
    //these == signs are really important
    }