0
votes

I am successfully able to fetch the documents from the firestore collection in flutter application and create a list view builder. Apart from this I want to create a list of particular field which is common to all documents in collection.

For example , every document has common field of username and after fetching all the documents from the firestore collection I want to create a list of usernames List usernames = []; in which I can add all the usernames from the collection.

Query query2 =   FirebaseFirestore.instance
        .collection('users');


StreamBuilder<QuerySnapshot>(
                 stream: query2.snapshots(),

              builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot) {

                if (snapshot.hasError) {
                  return Text('Something went wrong');
                }

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Text("Loading");
                }

                return ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index){

                    return ListTile(title:Text(snapshot.data.docs[index]['username'] ?? "",
                                    subtitle:Text(snapshot.data.docs[index]['email'] ?? ""
                  ),);
                  });
                }
              )

The above code is working fine all I want to create a separate list to use for the Usernames List usernames = [];

How can I do it ? Please Advise

2

2 Answers

0
votes
var usernames = snapshot.data.docs.map((e) => e['username']);
0
votes

Try this :

Query query2 = FirebaseFirestore.instance .collection('users').where("username",isNull: false );

StreamBuilder( stream: query2.snapshots(),

          builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot) {

            if (snapshot.hasError) {
              return Text('Something went wrong');
            }

            if (snapshot.connectionState == ConnectionState.waiting) {
              return Text("Loading");
            }

            return ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (context, index){

                return ListTile(title:Text(snapshot.data.docs[index]['username'] ?? "",
                                subtitle:Text(snapshot.data.docs[index]['email'] ?? ""
              ),);
              });
            }
          )

What this basically does is check the whole collection and returns the data where username is not null.