我正在尝试获取集合中具有等于特定字符串的特定字段的文档。我正在建立一个 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();
}
我收到这个错误:
A value of type 'Future<QuerySnapshot<Object?>>' can't be assigned to a variable of type 'CollectionReference<Object?>'.
我有投加投as 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,
),
),
);
},
);
}
}
最佳答案
您收到以下错误:
A value of type 'Future<QuerySnapshot<Object?>>' can't be assigned to a variable of type '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(...);
关于firebase - 获取具有等于特定字符串的字段的 Firestore 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69479844/