【问题标题】:How to return value on async function in flutter?如何在颤动中返回异步函数的值?
【发布时间】:2019-08-29 05:05:24
【问题描述】:

这是我的代码

SharedPreferences sharedPreferences;

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

当我打印时,我在调试控制台上收到了这条消息

Instance of 'Future<dynamic>'

我怎样才能得到“lorem ipsum...”的字符串?非常感谢

【问题讨论】:

标签: dart flutter


【解决方案1】:

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

SharedPreferences sharedPreferences;

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

token().then((value) {
  print(value);
});

但是有一个更好的方法来使用 SharedPreferences。检查文档here

【讨论】:

    【解决方案2】:

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

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

    检查Ios权限的功能

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

    在getToken函数中接收返回值

    Future<void> getToken() async {
      tokenId = await getUserToken();
    }
    
    print("token " + tokenId);
    

    【讨论】:

      【解决方案3】:

      只要函数是async,您需要使用 await 来响应它,否则 Instance of 'Future' 将被输出

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 2021-03-04
        • 2022-07-11
        • 2020-07-29
        • 2019-11-22
        • 2020-08-19
        • 1970-01-01
        • 1970-01-01
        • 2020-09-19
        相关资源
        最近更新 更多