如何在颤振中返回异步函数的值?

Ash*_*tav 9 dart flutter

这是我的代码

SharedPreferences sharedPreferences;

  token() async {
    sharedPreferences = await SharedPreferences.getInstance();
    return "Lorem ipsum dolor";
  }
Run Code Online (Sandbox Code Playgroud)

打印时,我在调试控制台上收到此消息

Instance of 'Future<dynamic>'
Run Code Online (Sandbox Code Playgroud)

我如何获得“lorem ipsum ...”的字符串?太感谢了

div*_*ava 16

token()是异步的,这意味着它返回Future. 你可以得到这样的值:

SharedPreferences sharedPreferences;

Future<String> token() async {
  sharedPreferences = await SharedPreferences.getInstance();
  return "Lorem ipsum dolor";
}

token().then((value) {
  print(value);
});
Run Code Online (Sandbox Code Playgroud)

但是有一个更好的方法来使用 SharedPreferences。在此处查看文档。


小智 6

为了从异步函数中检索任何值,我们可以查看以下从异步函数返回字符串值的示例。此函数以字符串形式从 firebase 返回令牌。

Future<String> getUserToken() async {
 if (Platform.isIOS) checkforIosPermission();
 await _firebaseMessaging.getToken().then((token) {
 return token;
 });
}
Run Code Online (Sandbox Code Playgroud)

检查Ios权限的函数

void checkforIosPermission() async{
    await _firebaseMessaging.requestNotificationPermissions(
        IosNotificationSettings(sound: true, badge: true, alert: true));
    await _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
}
Run Code Online (Sandbox Code Playgroud)

在函数getToken中接收返回值

Future<void> getToken() async {
  tokenId = await getUserToken();
}

print("token " + tokenId);
Run Code Online (Sandbox Code Playgroud)