Home > Mobile >  How to turn this function into a future?
How to turn this function into a future?

Time:06-01

I think I'll get chewed out for asking this question but I've been searching for a while and would like a little help!

I have this piece of code. How would I abandon having to use the callback and just return a future.


void getProducts({required Function() callback}) {
    List<Product> results = [];
    _firestore
        .collection('available_products')
        .get()
        .then((QuerySnapshot querySnapshot) {
      for (var doc in querySnapshot.docs) {
        print(doc);
        results.add(Product(
            name: doc['name'],
            category: doc['category'],
            description: doc['description'],
            price: doc['price']));
      }
      allProducts = results; 
      callback();
    }).onError((error, stackTrace) {
      print(error);
    });
  }

CodePudding user response:

Instead of void use the data type you want to return, List<Product>.
The rest of the code is just converting .then to async await syntax. You can still use the .then syntax though. This is just easier to understand IMO.

Here's the code snippet.

Future<List<Product>> getProducts() async {
  List<Product> results = [];

  try {
    final querySnapshot =
        await _firestore.collection('available_products').get();

    for (var doc in querySnapshot.docs) {
      print(doc);
      results.add(Product(
            name: doc['name'],
            category: doc['category'],
            description: doc['description'],
            price: doc['price']
          ));
    }

      allProducts = results;
  } catch (error) {
    print(error);
  }

  return results;
}

Further, you can return any other data types in place of List<Product>.

CodePudding user response:

Try with this

Future<void> getProducts({required Function() callback}) async{
    List<Product> results = [];
    await _firestore
        .collection('available_products')
        .get()
        .then((QuerySnapshot querySnapshot) {
      for (var doc in querySnapshot.docs) {
        print(doc);
        results.add(Product(
            name: doc['name'],
            category: doc['category'],
            description: doc['description'],
            price: doc['price']));
      }
      allProducts = results; 
      callback();
    }).onError((error, stackTrace) {
      print(error);
    });
  }
  • Related