Mayvas
Mayvas

Reputation: 789

Get array of ID from Firebase (DART/Flutter)

Is there any way to fetch data from Firebase with an array of documents. Now I do this with loop. It works but maybe there is some more efficient way to fetch data? Members list can contain up to 10k users so create 10k requests seems wrong.

Many thanks!

ref = db.collection('users');

  Future<List<User>> fetchAllMembers({List<dynamic> members}) async {
    List<User> results = [];

    for (String userID in members) {
      await ref.document(userID).get().then((result) {
        results.add(User.fromMap(result.data, result.documentID));
      });
    }

    return results;
  }

Upvotes: 2

Views: 1760

Answers (2)

Mayvas
Mayvas

Reputation: 789

SOLVED

So simple :). Working example below. Many thanks!

 final Firestore db = Firestore.instance;
 ref = db.collection('users');

List<dynamic> membersIDS = ['DSGSGSG', 'IBIOSCP3S', 'ASDUASDGU'];

  /// Fetch members list
  Future<List<User>> fetchAllMembers({List<dynamic> membersIDS}) async {

    /// With whereIn
    var result = await ref.where('uid', whereIn: members).getDocuments();
    var documents = result.documents.map((doc) => User.fromMap(doc.data, doc.documentID)).toList();
    return documents;

    /// With loop
    // List<User> results = [];
    // for (String userID in members) {
    //  await ref.document(userID).get().then((result) {
    //    results.add(User.fromMap(result.data, result.documentID));
    //  });
    // }
    // return results;
  }

Upvotes: 1

Kahou
Kahou

Reputation: 3488

Query documents where the given field matches any of the comparison values

userRef.where('id', 'in',
    [['DSGSGSG', 'IBIOSCP3S', 'ASDUASDGU']]);

Upvotes: 0

Related Questions