16

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

1

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.