Home > Blockchain >  Data not store in List variable while use stream builder
Data not store in List variable while use stream builder

Time:12-08

when I used Firestore query data stored in list variable but when I try to use this data outside the query it won't work. Please help me where I'm making mistake.

 List<ContactsModelClass> _groupContactList1 ; //declare list variable 
                  _groupCollection
                      .doc(widget.groupId)
                      .collection("groupContactList")
                      .get()
                      .then((docs) {
                    showLog('--->>>>>>${docs.docs.length}');
                    _groupContactList1 = List<ContactsModelClass>.generate(
                      docs.docs.length,
                      (index) => ContactsModelClass.fromJson(
                        docs.docs[index].data(),
                      ),
                    );  //Store data in list variable
                    print("init groupList:[${_groupContactList1.length}]"); //get data 
                  });                   
                  print(
                      "groupContactList list data:[${_groupContactList1.length}]"); // can not access data which store above in code. why?

CodePudding user response:

Because then callback is called later, where you set your _groupContactList1 . But you print _groupContactList1.lenght now, which is not set yet.

Use await instead, try solution below:

var docs = await _groupCollection.doc(widget.groupId).collection("groupContactList").get();
showLog('--->>>>>>${docs.docs.length}');
_groupContactList1 = List<ContactsModelClass>.generate(
 docs.docs.length,
 (index) => ContactsModelClass.fromJson(docs.docs[index].data()),
);
print("groupContactList list data:[${_groupContactList1.length}]");

CodePudding user response:

You need to put the await keyword for the fetching of docs from the Firestore. Once Firestore fetches the data then display or use the list.

  • Related