[英]How to get Firestore Data by method in Flutter
I am trying to get users name but Flutter gives this error:我正在尝试获取用户名,但 Flutter 出现此错误:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
Method:方法:
String getUserNameFromUID(String uid) {
FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
return doc["name"];
});
});
}
How can I solve my problem?我该如何解决我的问题? if I add return 0 to end of the method it always gives 0.如果我将 return 0 添加到方法的末尾,它总是给出 0。
It always gives 0.(I do not want 0, I want get user name from uid)它总是给 0。(我不想要 0,我想从 uid 获取用户名)
String getUserNameFromUID(String uid) {
FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
return doc["name"];
});
});
return "0";
}
First your function should return a Future<String>
since it relies on firestore's get
wich also returns a future.首先你的函数应该返回一个Future<String>
因为它依赖于 firestore 的get
也返回一个未来。 Also docs
is a list, you have to return just one.另外docs
是一个列表,你只需要返回一个。 The first one i guess.第一个我猜。 In the UI just use a FutureBuilder
在 UI 中只需使用FutureBuilder
Future<String> getUserNameFromUID(String uid) async {
final snapshot = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get();
return snapshot.docs.first['name'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.