简体   繁体   中英

Flutter Firestore doc get returning null

I am trying to get a document from a Firestore collection using the following code:

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. Is there a reason why this value isn't being returned in home_view.dart ?

This is an async operation and you have to await for its value.

For reference, you can take a look here at documentation of how propper authentication and CRUD operations made in Firebase with flutter.

Your code needs a few edits, as the getProfile function is 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
    });
  }
}

Then finally in home_view.dart

// insert await here:
Map<String, dynamic> profile = await
        firebaseService.getProfile(auth.currentUser.uid);

If you plan to use the getProfile function I suggest you to use a FutureBuilder . In you home_view.dart 's build function write this:

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();
});

And now you don't need to write:

Map<String, dynamic> profile = await
        firebaseService.getProfile(auth.currentUser.uid);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM