Home > OS >  Flutter Firebase getting list of document
Flutter Firebase getting list of document

Time:12-03

When I want to get data as object list

 onPressed: () {
     print("entered");
     ProductServices _productServives = ProductServices();
     Future<List<dynamic>> plist = _productServives.getProducts2();
     print(plist);
  },
Future<List<dynamic>> getProducts2() async {
    CollectionReference ref = _firestore.collection('Products');
    List<Product> productsArray = [];

    ref.snapshots().forEach((element) {
      element.docs.forEach((value) {
        var p = Product.fromSnapshot(value);
        productsArray.add(p);
        print("size: "   productsArray.length.toString());
      });
      // productsArray.add(element);
    });
    print("  size: "   productsArray.length.toString());

    return productsArray;
  }

It is not working as I want line by line. In for each putting element to the list and increasing the size but because of the working queue returned list is empty.

How can I fix this issue and where can I study asynchronous operation.

Output:

I/flutter (29128): entered
I/flutter (29128):   size: 0
I/flutter (29128): Instance of 'Future<List<dynamic>>'
I/flutter (29128): size: 1
I/flutter (29128): size: 2
I/flutter (29128): size: 3

CodePudding user response:

Since you already marked the function as async, you can use await inside it to mask the asynchronicity a bit:

Future<List<dynamic>> getProducts2() async {
  CollectionReference ref = _firestore.collection('Products');
  List<Product> productsArray = [];

  var snapshots = await ref.snapshots()
  snapshots.forEach((element) {
    element.docs.forEach((value) {
      var p = Product.fromSnapshot(value);
      productsArray.add(p);
      print("size: "   productsArray.length.toString());
    });
  });
  print("  size: "   productsArray.length.toString());

  return productsArray;
}

To learn more about futures, and async/await in Flutter: https://www.google.com/search?q=futures, and async/await in Flutter. In fact, I'm gonna add the first video from that search to my playlist as Andrew is a great explainer.

CodePudding user response:

I solved the issue coding like this

await ref.snapshots().first.then((value) => {
          value.docs.forEach((element) {
            print(element.id);
            var p = Product.fromSnapshot(element);
            productsArray.add(p);
          })
        });
  • Related