简体   繁体   English

获取字段等于 flutter 中特定字符串的 Firestore 文档

[英]Get Firestore documents with a field that is equal to a particular string in flutter

I am trying to get documents in a collection that have a particular field that equals a particular string.我正在尝试获取集合中具有等于特定字符串的特定字段的文档。 I am building a POS and I want to get all the sales for a particular city.我正在建立一个 POS,我想获得特定城市的所有销售额。

final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final CollectionReference _mainCollection = _firestore.collection('Sales');


  Stream<QuerySnapshot> readFeeds() {
    CollectionReference notesItemCollection =
    _mainCollection.where('seller_location', isEqualTo: "London").get();

    return notesItemCollection.snapshots();
  }

I am getting this error:我收到此错误:

A value of type 'Future<QuerySnapshot<Object?>>' can't be assigned to a variable of type 'CollectionReference<Object?>'.不能将“Future<QuerySnapshot<Object?>>”类型的值分配给“CollectionReference<Object?>”类型的变量。

I have cast added cast as CollectionReference<Object?>;我已将 added cast as CollectionReference<Object?>; but the query is still not working.但查询仍然无效。 This is how I am accessing the data:这就是我访问数据的方式:

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: readFeeds(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        } else if (snapshot.hasData || snapshot.data != null) {
          return ListView.separated(
            separatorBuilder: (context, index) => SizedBox(height: 16.0),
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) {
              var noteInfo = snapshot.data!.docs[index];
              String docID = snapshot.data!.docs[index].id;
              String name = noteInfo['name'].toString();
              String price = noteInfo['price'].toString();
              String quantity = noteInfo['quantity'].toString();
              return Ink(
                decoration: BoxDecoration(
                  color: CustomColors.firebaseGrey.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: ListTile(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  onTap: () => Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => EditScreen(
                        documentId: docID,
                        currentName: name,
                        currentPrice: price,
                        currentQuantity: quantity,
                      ),
                    ),
                  ),
                  title: Text(
                    name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              );
            },
          );
        }
        return Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(
              CustomColors.firebaseOrange,
            ),
          ),
        );
      },
    );
  }
}

You are getting the following error:您收到以下错误:

A value of type 'Future<QuerySnapshot<Object?>>' can't be assigned to a variable of type 'CollectionReference<Object?>'.不能将“Future<QuerySnapshot<Object?>>”类型的值分配给“CollectionReference<Object?>”类型的变量。

Because of the following line of code:因为下面一行代码:

CollectionReference notesItemCollection =
    _mainCollection.where('seller_location', isEqualTo: "London").get();

Which makes sense, since the get() function returns aFuture and not a CollectionReference object. There is no way in Dart in which you can create such a casting, hence that error.这是有道理的,因为get() function 返回一个Future不是CollectionReference object。在 Dart 中没有办法创建这样的转换,因此出现错误。

Since you are using the where() function, the type of the object that is returned is Query .由于您使用的是where() function,因此返回的 object 的类型是Query So your code should look like this:所以你的代码应该是这样的:

Query queryBySellerLocation =
    _mainCollection.where('seller_location', isEqualTo: "London");

Once you have this query correctly defined, you can perform the get() call, and collect the results:正确定义此查询后,您可以执行 get() 调用并收集结果:

queryBySellerLocation.get().then(...);

Please try this if it helps.如果有帮助,请试试这个。

QuerySnapshot<Map<String,dynamic>>readFeeds() {
   QuerySnapshot<Map<String,dynamic>>response=await   _mainCollection.where('seller_location', isEqualTo: "London").get()

return response;
  }

you can access this data like this你可以像这样访问这些数据

response.docs.forEach((element) {
        ///this is Map<String,dynamic>
        element.data();
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM