簡體   English   中英

Flutter Firestore 文檔返回 null

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM