firebase Flutter相关Firestore查询

oyxsuwqo  于 2023-01-18  发布在  Flutter
关注(0)|答案(4)|浏览(96)

我如何使用FlutterFire中的.where()来执行Firestore的查询?因为文档和示例没有涉及这个问题,所以我很困惑。我在这里没有找到其他问题,所以我希望我没有重复提问。

ctehm74n

ctehm74n1#

下面的例子遍历集合“fields”中的每个文档,并过滤“grower”。没有相关文档,但您可以检查源代码。

import 'package:cloud_firestore/cloud_firestore.dart';

Firestore.instance.collection('fields').where('grower', isEqualTo: 1)
    .snapshots().listen(
          (data) => print('grower ${data.documents[0]['name']}')
    );

来自源代码:

Query where(
    String field, {
    dynamic isEqualTo,
    dynamic isLessThan,
    dynamic isLessThanOrEqualTo,
    dynamic isGreaterThan,
    dynamic isGreaterThanOrEqualTo,
    bool isNull,
  }) {..}
xurqigkl

xurqigkl2#

更新(空安全代码)

由于很多类现在要么被弃用,要么被完全删除,因此请在Flutter 2.0及更高版本中使用此代码。

final querySnapshot = await FirebaseFirestore.instance
    .collection('employees')
    .limit(10)
    .where('age', isGreaterThan: 30)
    .get();

for (var doc in querySnapshot.docs) {
  // Getting data directly
  String name = doc.get('name');
  
  // Getting data from map
  Map<String, dynamic> data = doc.data();
  int age = data['age'];
}
2vuwiymt

2vuwiymt3#

这如果你使用streambuilder

StreamBuilder<QuerySnapshot>(
        stream: feed.where('uid', isEqualTo: 'aaaaaaaaaaaaa').snapshots(),
        builder: (_, snapshot) {
          if (snapshot.hasData) {
            return Column(
              children: snapshot.data.docs
                  .map((e) => itemGrid(
                        e.data()['username'],
                        e.data()['uid'],
                        e.data()['uavatarUrl'],
                        e.data()['imageUrl'],
                        e.data()['desc'],
                      ))
                  .toList(),
            );
          } else {
            print('null');
            return Container();
          }
        }));
cpjpxq1n

cpjpxq1n4#

使用null safety更新2023

示例数据

首先,写一些关于城市的数据,这样我们就可以用不同的方法来读回这些数据:

final cities = db.collection("cities");
final data1 = <String, dynamic>{
  "name": "San Francisco",
  "state": "CA",
  "country": "USA",
  "capital": false,
  "population": 860000,
  "regions": ["west_coast", "norcal"]
};
cities.doc("SF").set(data1);

final data2 = <String, dynamic>{
  "name": "Los Angeles",
  "state": "CA",
  "country": "USA",
  "capital": false,
  "population": 3900000,
  "regions": ["west_coast", "socal"],
};
cities.doc("LA").set(data2);

final data3 = <String, dynamic>{
  "name": "Washington D.C.",
  "state": null,
  "country": "USA",
  "capital": true,
  "population": 680000,
  "regions": ["east_coast"]
};
cities.doc("DC").set(data3);

final data4 = <String, dynamic>{
  "name": "Tokyo",
  "state": null,
  "country": "Japan",
  "capital": true,
  "population": 9000000,
  "regions": ["kanto", "honshu"]
};
cities.doc("TOK").set(data4);

final data5 = <String, dynamic>{
  "name": "Beijing",
  "state": null,
  "country": "China",
  "capital": true,
  "population": 21500000,
  "regions": ["jingjinji", "hebei"],
};
cities.doc("BJ").set(data5);

简单查询

1.以下查询返回州CA的所有城市:

// Create a reference to the cities collection
final citiesRef = db.collection("cities");

// Create a query against the collection.
final query = citiesRef.where("state", isEqualTo: "CA");

1.以下查询返回所有首都城市:

final capitalcities =
    db.collection("cities").where("capital", isEqualTo: true);

执行查询

创建查询对象后,使用get()函数检索结果:

db.collection("cities").where("capital", isEqualTo: true).get().then(
      (res) => print("Successfully completed"),
      onError: (e) => print("Error completing: $e"),
    );

有关详细信息,请参阅文档

相关问题