我想要这个方法的返回类型 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,
),
),
由于您的方法返回
Future
,因此您必须 await
它。所以你需要做 checkFav = await checkFavourite(quote_id)
而不是 checkFav = checkFavourite(quote_id) as bool