firebasedartflutterasync-awaitgoogle-cloud-firestore

How to call await correctly?


I'm new to Flutter and Dart. I have a following code:

class ItemRepository {

  final Firestore _firestore = Firestore.instance;

  Future<List<Item>> loadItems() async {
    List<Item> itemList = [];
    _firestore.collection('items').snapshots().listen((data) {
      data.documents.forEach((doc){
        print("------- KODE: ${doc['kode']}");
        itemList.add(Item(doc['kode'], doc['name']));
      });
    });
    return itemList;
  }
}

When I call my loadItems with following code:

Stream<ItemState> _mapLoadItemsToState() async* {
    try {
      final data = await this.repo.loadItems();
      print('-------------------------------');
      print(data.length);
    } catch(e) {
      print(e.toString());
    }
  }

It's not WAIT to data return from firebase. I added await to _firestore.collection('items').snapshots() but no luck.

Any idea? Thank for any advice. Sorry for poor English.


Solution

  • That's because you are listening the data, you will need to get the Future<QuerySnapshot> then the documents . Try something like this :

    Future<List<Item>> loadItems() async {
       final List<Item> itemList = (await Firestore.instance.collection('items').getDocuments()).documents.map((snapshot) => Item(doc['kode'], doc['name'])).toList();
       return itemList;
    }