Home > Blockchain >  Using where clauses in firestore query with a list in parameter
Using where clauses in firestore query with a list in parameter

Time:01-24

I would like to use a where clause in my Firestore query, with a list in parameter. I used a for loop to do this but when I want to add all my values in a variable, I have some problems with the add function (variable type problem). I understand the problem but I don't what is the way I have to take to do this in another way ... Can anyone help me? Best regards :) ###It's my first question on stack! :D ###

in my main class:

    var games = [
      "uno",
      "poker",
    ];

    return StreamProvider<List<AppUserData>>.value(
      initialData: [],
      value: DatabaseService().users4(games),
      child: Scaffold(....

in my database class

  List<AppUserData> _list = [];
  void addToList(AppUserData value) {
    _list.add(value);
  }

  Stream<List<AppUserData>> users4 (List games) {
    print(games);
    var b;
    var len = games.length;
    for (var i = 0; i < len   1; i  ) {
      b = FirebaseFirestore.instance.collection("users")
          .where("games", isEqualTo: games[i]).snapshots().map(
          _userListFromSnapshot);
      print("$b");
      addToList(b);
    }
    return b;
  }

  List<AppUserData> _userListFromSnapshot(
      QuerySnapshot<Map<String, dynamic>> snapshot) {
    return snapshot.docs.map((doc) {
      return _userFromSnapshot(doc);
    }).toList();
  }

  AppUserData _userFromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot) {
    var data = snapshot.data();
    if (data == null) throw Exception("user not found");
    return AppUserData(
      uid: uid,
      name: snapshot.data()['name'],
      distance: snapshot.data()['distance'],
      games: snapshot.data()['games'],
      id: snapshot.data()['id'],
    );
  }

CodePudding user response:

I think you're looking for whereIn

Try this:

  Stream<List<AppUserData>> users4(List games) async* {
    yield* FirebaseFirestore.instance
        .collection("users")
        .where("games", whereIn: games)
        .snapshots()
        .map((e) {
      List<AppUserData> l =
          e.docs.map((e) => _userFromMap(Map.from(e.data()))).toList();
      return l;
    });
  }


 AppUserData _userFromMap(Map<String, dynamic> map) {
    if (map == null) throw Exception("user not found");
    return AppUserData(
      uid: uid,
      name: map['name'],
      distance: map['distance'],
      games: map['games'],
      id: map['id'],
    );
  }

  •  Tags:  
  • Related