1

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'],
    );
  }

1 Answer 1

1

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'],
    );
  }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.