【问题标题】:Using where clauses in firestore query with a list in parameter在firestore查询中使用where子句和参数列表
【发布时间】:2022-01-23 14:19:57
【问题描述】:

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

在我的主要课程中:

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

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

在我的数据库类中

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

【问题讨论】:

    标签: list flutter dart google-cloud-firestore where-clause


    【解决方案1】:

    我想你在找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'],
        );
      }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多