我面临错误类型“Future<bool?>”不是类型转换中“bool”类型的子类型

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

我想要这个方法的返回类型 bool 并依赖于我渲染的 UI

全局变量 bool checkFav = false;
在每个页面视图上我想调用此方法来显示最喜欢的图标

 Future<bool?> checkFavourite(int id) async {
    final url = Uri.parse('https://quotes.limpidsol.com/api/favourite');
    var pref = await SharedPreferences.getInstance();
    final response = await http.post(
      url,
      body: {'qoute_id': id.toString()},
      headers: {"Authorization": "Bearer ${pref.getString('token')}"},
    );
    if (response.statusCode == 200) {
      final Map<String, dynamic> responseData = jsonDecode(response.body);
      String message = responseData['message'];
      if (message == 'Qoute favourite successfully') {
        print('ok');
        return true;
      }
    }
    return null;
  }

pageView中的方法调用::>> checkFav = checkFavourite(quote_id) as bool;

取决于 future 的返回值(true/false) 我更新用户界面而不加载

 IconButton(
                            onPressed: () {
                              checkFav
                                  ? handleRemoveToFav(quoteList[index]['id'])
                                  : handleAddToFav(quoteList[index]['id']);
                            },
                            icon: Icon(
                              checkFav
                                  ? Icons.favorite_outlined
                                  : Icons.favorite_border,
                              color: checkFav ? Colors.red : Colors.grey,
                              size: 30.0,
                            ),
                          ),

FutureBuilder 返回一些小部件或进度指示器,但 scanrio 不同,请查看图片 please view picture

flutter dart
1个回答
0
投票

由于您的方法返回

Future
,因此您必须
await
它。所以你需要做
checkFav = await checkFavourite(quote_id)
而不是
checkFav = checkFavourite(quote_id) as bool

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