Flutter & Firebase: How to check if an item exists inside of an array within a Firebase document

Issue

img_firebase

I’m trying to waitUser(array) check exist value how can I?

// if waitUser array field exist 2 return text("this text") else return text("other text")

      body: StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('events')
        .where('eventCity', isEqualTo: 'Ankara')
        .snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData) {
        // ERROR
        return Center(
          child: CircularProgressIndicator(),
        );
      } else {
        return Container(
          child: ListView(
            scrollDirection: Axis.vertical,
            children: snapshot.data.docs.map((document) {
              // if waitUser array field exist 2 return text("this text") else return text("other text")
            }).toList(),
          ),
        );
      }
    },
  ),

Solution

In the else portion of your builder do this:

return Container(
          child: ListView(
            scrollDirection: Axis.vertical,
            children: snapshot.data.docs.map((document) {
              // Get the waitUser array from the document.
              List<dynamic> waitUser = document.data()["waitUser"] as List<dynamic>;

              // Check for "2" in the array.
              if (waitUser.contains("2")) {
                // "2" was in the array.
                return text("this text");
              } else {
                // "2" was not in the array.
                return text("other text");
              }
            }).toList(),
          ),
        );

This will gather each document that meets your criteria of eventCity == "Ankara". For each of those documents, it will check the waitUser array for "2". If "2" exists in the array, it will return text("this text"); otherwise, it will return text("other text").

Answered By – JebediahTheAmishProgrammer

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.