Home > database >  flutter firestore: how to get a query of documents
flutter firestore: how to get a query of documents

Time:10-18

Im trying to get a list of user objects from firestore through a query. My current attempt looks like this:

List<User> getDiscoveryUsers(
    String userId,
  ) async {
    Query<Object?> query =
        userCollection.where('finishedOnboarding', isEqualTo: true).limit(10);

    var collection = await query.get();
    //get the users list from query snapshot
    var users = collection.docs.map((doc) => User.fromSnapshot(doc)).toList();

    return users;
  }

However I am getting the error:

Functions marked 'async' must have a return type assignable to 'Future'.
Try fixing the return type of the function, or removing the modifier 'async' from the function body.

I know there are a few similar questions on stack overflow, but i just cant seem to get this to work. Anyone know whats going on?

Thanks!

CodePudding user response:

Just change the return type of your function from List<User> to Future<List<User>>.

Happy coding:)

CodePudding user response:

your return type should be Future and must wait with await when running query on firestore.

Future<List<User>> getDiscoveryUsers(
    String userId,
  ) async {
    Query<Object?> query =
        userCollection.where('finishedOnboarding', isEqualTo: true).limit(10);

    var collection = await query.get();
    //get the users list from query snapshot
    var users = collection.docs.map((doc) => User.fromSnapshot(doc)).toList();

    return users;
  }
  • Related