I am trying to get a user bio and write it in another document in a different collection but I get an Instance of future<dynamic> in my database

Viewed 26

I want to create a function that writes to the Firebase firestore collection of posts and I want it to automatically add the username of the current user but when the app writes to firebase for the field of the username it returns Instance of Future. Here is my code

class FireStoreMethods {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  Future<String> uploadPost(
    String title,
    String description,
    Uint8List file,
  ) async {
   
    String res = "Some error occurred";

    Future getUserName<String>() async {
      var userData = {};
      var userDetails = await _firestore
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .get();
      userData = userDetails.data()!;
      String username = await userData['username'];
      return username;
    }

    try {
      if (title.isNotEmpty || description.isNotEmpty || file.isNotEmpty) {
        String photoUrl =
            await StorageMethods().uploadImagePostPicToStorage('posts', file);
        String postId = const Uuid().v1(); 
        Post post = Post(
            postId: postId,
            title: title,
            description: description,
            datePublished: DateTime.now(),
            postPhotoUrl: photoUrl,
            userEmail: _firebaseAuth.currentUser!.email.toString(),
            userName: getUserName().toString());

        await _firestore.collection('posts').doc(postId).set(post.toJson());
        res = "success";
      }
    } catch (err) {
      res = err.toString();
    }
    return res;
  }
}
1 Answers

put await when calling getUserName().toString() as below

Post post = Post(
            postId: postId,
            title: title,
            description: description,
            datePublished: DateTime.now(),
            postPhotoUrl: photoUrl,
            userEmail: _firebaseAuth.currentUser!.email.toString(),
            userName: await getUserName().toString());

Just a note: The method declaration should be like this

Future<String> getUserName() async{}
Related