[英]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.