15

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

Ashtav
  • 2,586
  • 7
  • 28
  • 44
  • 1
    There's multiple ways, but seems you might want to read the docs https://www.dartlang.org/tutorials/language/futures Note that SharedPreferences don't need to be asynchronous – OneCricketeer Apr 08 '19 at 05:39

3 Answers3

24

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.

TheMisir
  • 4,083
  • 1
  • 27
  • 37
divyanshu bhargava
  • 1,513
  • 1
  • 13
  • 24
6

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);
Rana Hyder
  • 363
  • 2
  • 10
0

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

Muhammad Umair Saqib
  • 1,287
  • 1
  • 9
  • 20