Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value on async function in flutter?

Tags:

flutter

dart

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

like image 647
Ashtav Avatar asked Apr 08 '19 05:04

Ashtav


People also ask

How do you call async function in Flutter?

You can declare an async function by adding an async keyword before the function body. 1 We don't need to explicitly return Future. value(1) here since async does the wrapping. If you try to remove the async keyword, you will get the following error.

How do I return to the Future void?

You don't need to return anything manually, since an async function will only return when the function is actually done, but it depends on how/if you wait for invocations you do in this function. When using Future<void> there is no need to explicitly return anything, since void is nothing, as the name implies.

How does async await work in Flutter?

Execution flow with async and await An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.


1 Answers

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);
like image 131
Aman Raj Srivastava Avatar answered Sep 17 '22 14:09

Aman Raj Srivastava