Home > Back-end >  Why am I getting 'Future<dynamic>' instead of the return value in the function?
Why am I getting 'Future<dynamic>' instead of the return value in the function?

Time:10-24

I'm trying to get the return value in my function but the output is 'Instance of Future' instead of the value of school field name in the database

         @override
      void initState() {
        userId = _auth.currentUser!.uid;
        publisherSchool =
            getName(widget.postInfo['publisher-Id'], 'school').toString();
        super.initState();
      }

  Future getName(String publisherUid, String fieldname) async {
    DocumentSnapshot publisherSnapshot = await FirebaseFirestore.instance
        .collection('users')
        .doc(publisherUid)
        .get();
    print(publisherSnapshot.get(fieldname));
    return publisherSnapshot.get(fieldname);
  }

but whenever i'm printing the publisherSnapshop.get(fieldname) i'm getting the correct value from the database

CodePudding user response:

When you declare the getName() function, specify the return type as Future<String>, and then when you call getName(), you need to await the result e.g. publisherSchool = await getName(widget.postInfo['publisher-Id'], 'school').toString();

CodePudding user response:

There are 2 ways to do it, you can create a Future method and call it inside the initState like below:

@override
void initState() {
   initial();
   super.initState();
}

Future<void> initial() async {
  userId = _auth.currentUser!.uid;

  // Remember using `()` to wrap the `await` to get it result
  publisherSchool = (await getName(widget.postInfo['publisher-Id'], 'school')).toString();
}

Or you can use .then to call it directly inside the initState:

@override
void initState() {
  userId = _auth.currentUser!.uid;
  getName(widget.postInfo['publisher-Id'], 'school').then((value) {
     publisherSchool = value.toString();
  });
  super.initState();
}

CodePudding user response:

The reason why you are not getting the correct response is because whenever you are working with Futures it takes some time to finish and return the results. Meanwhile it is fetching the result you have to make it await so that the program will continue once that future function is complete since await/then is nowhere to be found in your code hence the issues.

To solve this make this change:

Change

 publisherSchool =
            getName(widget.postInfo['publisher-Id'], 'school').toString();

To

   getName(widget.postInfo['publisher-Id'], 
    'school').then((value){
    publisherSchool=value.toString()});
  • Related