Firebase 尝试从Firestore获取数据时出错
当我尝试使用此代码从firestore检索数据时Firebase 尝试从Firestore获取数据时出错,firebase,flutter,dart,google-cloud-firestore,firebase-authentication,Firebase,Flutter,Dart,Google Cloud Firestore,Firebase Authentication,当我尝试使用此代码从firestore检索数据时 Future<String> getUserType() async { await (Firestore.instance .collection('users') .document(getUserUID().toString()) .get() .then((DocumentSnapshot ds) {
Future<String> getUserType() async {
await (Firestore.instance
.collection('users')
.document(getUserUID().toString())
.get()
.then((DocumentSnapshot ds) {
return ds['type'];
}));
}
我还尝试:
return ds.data['type'];
检索用户uid的代码为:
Future<String> getUserUID() async {
return (await _firebaseAuth.currentUser()).uid;
}
Future getUserUID()异步{
返回(wait_firebaseAuth.currentUser()).uid;
}
但我不认为这是问题所在,可能在ds中什么都没有。您需要先检索
用户ID,然后在文档检索中使用它:
Future<String> getUserType() async {
String userID = (await _firebaseAuth.currentUser()).uid;
await (Firestore.instance
.collection('users')
.document(userID)
.get()
.then((DocumentSnapshot ds) {
return ds['type'];
}));
}
Future getUserType()异步{
字符串userID=(wait _firebaseAuth.currentUser()).uid;
等待(Firestore.instance)
.collection('用户')
.document(userID)
.get()
.然后((文档快照){
返回ds['type'];
}));
}
在代码中:
Future<String> getUserUID() async {
return (await _firebaseAuth.currentUser()).uid;
}
Future getUserUID()异步{
返回(wait_firebaseAuth.currentUser()).uid;
}
getUserUID()
返回一个Future
,但是当您执行.document(getUserUID().toString())
时,您不会得到该Future
的结果
检查以下各项:
您的getUserUID()方法返回一个未来字符串而不是常规字符串。因此,您无法通过提供该字符串直接获取文档。这是我实现类似函数的常用方法
Future<String> getUserType() async {
getUserUID().then((currentUser) {
if (currentUser != null) {
await (Firestore.instance
.collection('users')
.document(currentUser)
.get()
.then((DocumentSnapshot ds) {
return ds['type'];
}));
}
}
}
Future getUserType()异步{
getUserUID()。然后((当前用户){
如果(currentUser!=null){
等待(Firestore.instance)
.collection('用户')
.文档(当前用户)
.get()
.然后((文档快照){
返回ds['type'];
}));
}
}
}
如果用户没有文档怎么办?通常情况下,您会获得给定用户的文档列表,然后检查数据是否为空,然后在其中循环并检查类型。
Future<String> getUserType() async {
getUserUID().then((currentUser) {
if (currentUser != null) {
await (Firestore.instance
.collection('users')
.document(currentUser)
.get()
.then((DocumentSnapshot ds) {
return ds['type'];
}));
}
}
}