Sergio Bost
Sergio Bost

Reputation: 3249

How to turn this function into a future?

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);
    });
  }

Upvotes: 0

Views: 86

Answers (2)

nicks101
nicks101

Reputation: 1201

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>.

Upvotes: 3

Jahidul Islam
Jahidul Islam

Reputation: 12595

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);
    });
  }

Upvotes: 1

Related Questions