在带有参数列表的 firestore 查询中使用 where 子句

Using where clauses in firestore query with a list in parameter

我想在我的 Firestore 查询中使用 where 子句,并在参数中包含一个列表。 我使用 for 循环来执行此操作,但是当我想将所有值添加到变量中时,添加函数出现了一些问题(变量类型问题)。 我理解这个问题,但我不知道我必须采取什么方式才能以另一种方式做到这一点...... 谁能帮我? 最好的问候 :) ###It's my first question on stack! :D ###

在我的主要 class:

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

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

在我的数据库中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'],
    );
  }

我想你在找 whereIn

试试这个:

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