gpt4 book ai didi

if-statement - Flutter中的Future vs bool

转载 作者:行者123 更新时间:2023-12-03 02:55:25 28 4
gpt4 key购买 nike

我创建了如下的rest api方法,

  Future<bool> activateAccount(int id, int code) async{
final body = {"code": '$code'};

final response = await client.post(
'$baseUrl/user/account/$id',
body: body
);
if(response.statusCode == 200){
return true;
}else return false;
}

但我不能在 if语句中使用此方法,如下所示:
bool a = userApiService.activateAccount(...)
if(a){
...
}

因为:
A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'.

在什么问题上?
如何更改此方法以根据操作结果将其返回 bool(boolean) 值?

我想在我的 raisedButton中包含if语句:
 child: RaisedButton(
onPressed: () {
userApiService.activateAccount(sharedPreferences.getInt('newUserId'), int.parse(activeCode));
// sharedPreferences.clear();
},
child: Text("ENTER",
style: TextStyle(color: Colors.white, fontSize: 16.0, fontWeight: FontWeight.bold)),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(40.0)),
color: Colors.red,
)

最佳答案

这样退还比你还短的 bool(boolean) ;

Future<bool> activateAccount(int id, int code) async {
final body = {"code": '$code'};

final response = await client.post('$baseUrl/user/account/$id', body: body);
return response.statusCode == 200;
}

要使用返回值,您需要使用 await关键字;
bool a = await userApiService.activateAccount(...)
if(a){
...
}

与按钮一起使用时,只需在大括号前添加 async关键字;
onPressed: () async {
bool a = await userApiService.activateAccount(...)
if(a){
...
}
}

关于if-statement - Flutter中的Future <bool> vs bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61295346/

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