如何在flutter中返回async函数的值?

问题描述 投票:0回答:2

这是我的代码

SharedPreferences sharedPreferences;

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

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

Instance of 'Future<dynamic>'

我怎么能得到一串“lorem ipsum ......”?非常感谢

dart flutter
2个回答
3
投票

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

SharedPreferences sharedPreferences;

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

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

但是有一种更好的方法可以使用SharedPreferences。检查文档here

© www.soinside.com 2019 - 2024. All rights reserved.