Future<bool> vs bool in Flutter
242
Returning the bool like this shorter than yours;
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;
}
And to use return value is you need to use await
keyword;
bool a = await userApiService.activateAccount(...)
if(a){
...
}
for using with your button just add async
keyword before curly brackets;
onPressed: () async {
bool a = await userApiService.activateAccount(...)
if(a){
...
}
}
Author by
Admin
Updated on December 12, 2022Comments
-
Admin over 1 year
I created an rest api method like below,
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; }
but i can't use this method in
if
statement like this:bool a = userApiService.activateAccount(...) if(a){ ... }
because:
A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'.
in what is problem? how to change this method to return it boolean depending on the result of the operation?
I would like to include in my
raisedButton
if statement: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, )
-
Admin almost 4 yearscan you show how this
bool a = ...
can look in function? because I needasync
-
Mehmet Ali Bayram almost 4 yearsYes you need async function because you use a Future. For more detail you should put your code, where you use this
if (a)
, here