Home > Net >  How to check for an empty array in FirebaseFirestore using StreamBuilder flutter
How to check for an empty array in FirebaseFirestore using StreamBuilder flutter

Time:10-28

I have a StreamBuilder to check for an empty string But I want to turn it to check for an empty array. How can I do that?

bool? checkEmpty = false;

StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
              stream: FirebaseFirestore.instance
                  .collection('widgets')
                  .doc(widgets)
                  .snapshots(),
              builder: (context, snapshot) {
                snapshot.data?.data()?.forEach((key, value) {
                  if (key == 'imageUrl') {
                    checkEmpty = value == [];
                  }
                });
            return ...
                     checkEmpty!
                     ? Text('Array is not empty')
                     : Text('Empty array'),

enter image description here

CodePudding user response:

cast the value type as List then check over it.

try the following:

    bool? checkEmpty = false;

StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
              stream: FirebaseFirestore.instance
                  .collection('widgets')
                  .doc(widgets)
                  .snapshots(),
              builder: (context, snapshot) {
                snapshot.data?.data()?.forEach((key, value) {
                  if (key == 'imageUrl') {
                    checkEmpty = (value as List).isEmpty;
                  }
                });
            return ...
                     checkEmpty!
                     ? Text('Array is not empty')
                     : Text('Empty array'),
  • Related