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



我试图在一个集合中获得文档,该集合具有等于特定字符串的特定字段。我正在建立一个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();
}

我得到这个错误:

类型为"Future<Object?>>"的值不能赋值给类型为"CollectionReference<Object?>"的变量。

我已经添加了castas CollectionReference<Object?>;,但查询仍然不起作用。下面是我访问数据的方式:

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

您将得到以下错误:

类型为"Future<Object?>>"的值不能赋值给类型为"CollectionReference<Object?>"的变量。

因为以下代码行:

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

这是有意义的,因为get()函数返回一个Future并且不是CollectionReference对象。在Dart中没有办法创建这样的强制类型转换,因此出现了这个错误。

由于使用的是where()函数,因此返回的对象类型是Query。所以你的代码应该是这样的:

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

一旦正确定义了这个查询,就可以执行get()调用,并收集结果:

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

如果有帮助,请尝试一下。

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

你可以像这样访问这些数据

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