0

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?

2 Answers 2

2

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}]");
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.