[英]Flutter Firestore doc get returning null
我正在尝试使用以下代码从 Firestore 集合中获取文档:
firebase_service.dart:
class FirebaseService {
final firestoreInstance = FirebaseFirestore.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
Map<String, dynamic> getProfile(String uid) {
firestoreInstance.collection("Artists").doc(uid).get().then((value) {
return (value.data());
});
}
}
home_view.dart:
Map<String, dynamic> profile =
firebaseService.getProfile(auth.currentUser.uid);
When stepping through the code the profile variable is null in home_view.dart
, but value.data()
in firebase_service.dart contains a map. home_view.dart
中没有返回此值是否有原因?
这是一个async
操作,您必须await
它的值。
作为参考,您可以在此处查看有关如何在 Firebase 和 flutter 中进行正确身份验证和 CRUD 操作的文档。
您的代码需要进行一些编辑,因为getProfile
function 是async
。
class FirebaseService {
final firestoreInstance = FirebaseFirestore.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
// set the return type to Future<Map<String, dynamic>>
Future<Map<String, dynamic>> getProfile(String uid) async { // insert async here
/// insert a return and await here
return await firestoreInstance.collection("Artists").doc(uid).get().then((value) =>
return value.data(); // the brackets here aren't needed, so you can remove them
});
}
}
然后终于在home_view.dart
// insert await here:
Map<String, dynamic> profile = await
firebaseService.getProfile(auth.currentUser.uid);
如果您打算使用getProfile
function 我建议您使用FutureBuilder
。 在你home_view.dart
的build
function 写这个:
return FutureBuilder(
future: firebaseService.getProfile(auth.currentUser.uid),
builder: (context, snapshot){
if (!snapshot.hasData){
return Center(child: CircularProgressIndicator(),);
}
final Map<String, dynamic> profile = snapshot.data.data();
return YourWidgets();
});
现在你不需要写:
Map<String, dynamic> profile = await
firebaseService.getProfile(auth.currentUser.uid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.