gpt4 book ai didi

flutter - 如何在小部件中使用Future

转载 作者:行者123 更新时间:2023-12-03 04:59:50 27 4
gpt4 key购买 nike

我的提供者存储库中有一个Future函数。但是它是Future<bool>,因为我需要Httpt的async

Future<bool> hasCard() async {
String token = await getToken();
var body = jsonEncode({"token": token, "userID": user.getUserID()});

var res = await http.post((baseUrl + "/hasCard"), body: body, headers: {
"Accept": "application/json",
"content-type": "application/json"
});

print(res.toString());

if (res.statusCode == 200) {
this.paymentModel = PaymentModel.fromJson(json.decode(res.body));
return true;
}
return false;
}

在我的小部件中,我想检查以下值:
Widget build(BuildContext context) {
var user = Provider.of<UserRepository>(context);
if(user.hasCard())
{
//do something
}

但是我收到一条错误消息:

Conditions must have a static type of 'bool'.dart(non_bool_condition)



由于它是 Widget类型,因此我不能在这里使用 async。解决这个问题的方法可能是什么?

最佳答案

您可以使用FutureBuilder,它将根据future值构建窗口小部件,在future完成之前,该值将为null。这是一个例子。

FutureBuilder(
future: hasCard(),
builder: (context, snapshot) {
if (snapshot.data == null)
return Container(
width: 20,
height: 20,
child: CircularProgressIndicator());
if (snapshot.data)
return Icon(
Icons.check,
color: Colors.green,
);
else
return Icon(
Icons.cancel,
color: Colors.red,
);
},
)

关于flutter - 如何在小部件中使用Future <bool>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com