英文:
flutter firestore data read
问题
getData() async {
var a = await FirebaseFirestore.instance.collection('users').where('1_email', isEqualTo: currentUser.currentUser!.email).get();
print(a);
}
@override
void initState() {
getData();
super.initState();
}
Console:
> flutter: Instance of 'QuerySnapshot<Map<String, dynamic>>'
这段代码是用来从Firebase中拉取数据的,如果用户登录的邮箱与Firestore数据库中的邮箱匹配,请拉取数据。
然而,如果您尝试使用 print(a['1_email'])
,将会出现以下错误(如附图所示):
> 运算符 '[]' 未定义于类型 'QuerySnapshot<Map<String, dynamic>>'。 (Documentation) 请定义运算符 '[]'。
您想要如何获取下面的数据?
<details>
<summary>英文:</summary>
getData() async {
var a = await FirebaseFirestore.instance.collection('users').where('1_email', isEqualTo:currentUser.currentUser!.email).snapshots();
print(a);
}
@override
void initState() {
getData();
super.initState();
}
Console :
> flutter: Instance of '_MapStream<QuerySnapshotPlatform, QuerySnapshot<Map<String, dynamic>>>'
getData() async {
var a = await FirebaseFirestore.instance.collection('users').where('1_email', isEqualTo:currentUser.currentUser!.email).get();
print(a);
}
@override
void initState() {
getData();
super.initState();
}
Console :
> flutter: Instance of '_JsonQuerySnapshot'
The code above is, if the user's email logged in to the Firebase matches the email contained in the Firestore database, please pull the data
However, if you treat it as `print(a['1_email])`
the following error appears (pictured attached)
> The operator '[]' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>'. (Documentation) Try defining the operator '[]'.
![Error](https://i.stack.imgur.com/eoklx.png)
How can I get the data below?
![Firestore](https://i.stack.imgur.com/fMp6Q.png)
</details>
# 答案1
**得分**: 0
你正在执行一个查询,该查询可能会有多个结果。您的代码没有处理可能存在多个结果的情况。
为了正确处理一次性读取操作,可以使用以下代码更改:
```dart
getData() async {
var querySnapshot = await FirebaseFirestore.instance.collection('users').where('1_email', isEqualTo: currentUser.currentUser!.email).get();
for (var docSnapshot in querySnapshot.docs) {
print(docSnapshot.get("1_email"));
}
}
这个代码更改基本上可以从Firebase文档中关于执行查询的部分进行复制/粘贴。
英文:
You're executing a query, which can have multiple results. Your code doesn't handle the fact that there may be multiple results.
To handle this correctly with a one-time read operation, would be:
getData() async {
var querySnapshot = await FirebaseFirestore.instance.collection('users').where('1_email', isEqualTo:currentUser.currentUser!.email).get();
for (var docSnapshot in querySnapshot.docs) {
print(docSnapshot.get("1_email"));
}
}
The code change is pretty much copy/paste from the Firebase documentation section on executing a query.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论