Jack Quinn
Jack Quinn

Reputation: 25

Issue adding element to list

I'm a total newbie to Flutter and I'm trying to add some data from Cloud Firestore to a list in Flutter, but having issues. I try to add the element, but after executing, the element isn't there. It's not throwing an exception or anything either. Maybe someone else has some advice for me!

I have tried changing the type of list (capture the doc from Cloud Firestore instead of data within the doc, same issue), I have also debugPrinted the data I am trying to store to make sure it exists, it does. I have done basic troubleshooting like running flutter clean as well. I am on the latest version of Flutter.

Firestore db = firestore();

List<String> getString() {

var dataList = new List<String>();

db.collection('Users').get().then((querySnapshot) {
  querySnapshot.forEach((doc) {
    dataList.add(doc.get('First name'));
  });
});

debugPrint(dataList.first);

return dataList;

The list is empty, though it should contain the "First name" field on this Cloud Firestore doc. Again, verified the data does exist and prints when calling debugPrint.

Upvotes: 1

Views: 70

Answers (1)

Augusto
Augusto

Reputation: 4243

The db.collection('Users').get() is a async function, so debugPrint(dataList.first); executes before of the end of your firestores get, because that your array returns empty.

If you try it:

db.collection('Users').get().then((querySnapshot) {
  querySnapshot.forEach((doc) {
    dataList.add(doc.get('First name'));
  });
  debugPrint(dataList.first);
});

You will see your data.

You can use await to wait the call finishes, so you must return a Future and use async key word on function declaration. This is a conceipt that you must know of flutter async functions (Async Flutter). So, the code below can solve your problem.

Firestore db = firestore();

Future <List<String>> getString() async {

var dataList = new List<String>();

var result = await db.collection('Users').get();
result.forEach((doc) {
    dataList.add(doc.get('First name'));
  });

debugPrint(dataList.first);

return dataList;
}

Upvotes: 3

Related Questions