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
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With