【问题标题】:'Future<dynamic>' is not a subtype of type 'bool''Future<dynamic>' 不是 'bool' 类型的子类型
【发布时间】:2021-08-25 12:25:38
【问题描述】:

我有一个这样的checkLoginStatus()。它将返回truefalse

checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    print(sharedPreferences.getString("token"));
    if (sharedPreferences.getString("token") != null) {
      return true;
    }
    return false;
  }

我有一个button A,代码如下

press: () => {
if(checkLoginStatus()) {
      //..Some code
     } else {
      //..
     }
   }

我点击button A 得到

Another exception was thrown: type 'Future&lt;dynamic&gt;' is not a subtype of type 'bool'

为什么?以及如何在if() 条件下检查checkLoginStatus() 返回truefalse

【问题讨论】:

标签: flutter dart


【解决方案1】:
  • 添加return类型到checkLoginStatuslike
Future<bool> checkLoginStatus() async {
  //
}
  • 在 if 语句中等待 future 完成
() async => {
if(await checkLoginStatus()) {
  //
}

投射到Future&lt;bool&gt;

() async => {
if(await (checkLoginStatus() as Future<bool>)) {
  //
}

【讨论】:

    【解决方案2】:

    对于checkLoginStatus(),您必须使用await,因为目前它的类型为Future&lt;dynamic&gt;

    press: () => async {
    final _checkLoginStatus = await checkLoginStatus();
    if(_checkLoginStatus) {
          //..Some code
         } else {
          //..
         }
       }
    

    另外,一定要给你的方法一个返回类型。

    Future<bool> checkLoginStatus() async {
        sharedPreferences = await SharedPreferences.getInstance();
        print(sharedPreferences.getString("token"));
        if (sharedPreferences.getString("token") != null) {
          return true;
        }
        return false;
      }
    

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2020-09-24
      • 2020-09-11
      • 2020-10-13
      • 2021-02-10
      • 1970-01-01
      相关资源
      最近更新 更多