How to return value on async function in flutter?

20,696

Solution 1

token() is async which means it returns Future. You can get the value like this:

SharedPreferences sharedPreferences;

Future<String> token() async {
  sharedPreferences = await SharedPreferences.getInstance();
  return "Lorem ipsum dolor";
}

token().then((value) {
  print(value);
});

But there is a better way to use SharedPreferences. Check docs here.

Solution 2

In order to retrieve any value from async function we can look at the following example of returning String value from Async function. This function returns token from firebase as String.

Future<String> getUserToken() async {
 if (Platform.isIOS) checkforIosPermission();
 await _firebaseMessaging.getToken().then((token) {
 return token;
 });
}

Fucntion to check for Ios permission

void checkforIosPermission() async{
    await _firebaseMessaging.requestNotificationPermissions(
        IosNotificationSettings(sound: true, badge: true, alert: true));
    await _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
}

Receiving the return value in function getToken

Future<void> getToken() async {
  tokenId = await getUserToken();
}

print("token " + tokenId);
Share:
20,696
Ashtav
Author by

Ashtav

I am fullstack developer, I write code and also make music, I love to play guitar, drum, violin and piano.

Updated on March 17, 2021

Comments

  • Ashtav
    Ashtav over 3 years

    This is my code

    SharedPreferences sharedPreferences;
    
      token() async {
        sharedPreferences = await SharedPreferences.getInstance();
        return "Lorem ipsum dolor";
      }
    

    When I print, I got this message on debug console

    Instance of 'Future<dynamic>'
    

    How I can get string of "lorem ipsum..." ? thank you so much