Ashtav
Ashtav

Reputation: 2966

How to return value on async function in flutter?

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

Upvotes: 16

Views: 34904

Answers (3)

Muhammad Umair Saqib
Muhammad Umair Saqib

Reputation: 1835

Whenever the function is async you need to use await for its response otherwise Instance of 'Future' will be output

Upvotes: 0

Aman Raj Srivastava
Aman Raj Srivastava

Reputation: 314

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

Upvotes: 6

divyanshu bhargava
divyanshu bhargava

Reputation: 1585

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.

Upvotes: 26

Related Questions