I have a button which on initial click/tap/touch, it POST to API and return true or false based on auth.
onPressed: ()=>{ Provider.of<Login>(context, listen: false).login() .then((value) => { if(value == true) Navigator.pushReplacementNamed(context, '/home') }), },
Future<bool> login() async { try{ var payload = jsonEncode({ 'email': usrname, 'password': pswd }); Map<String,dynamic> response = await fetch.post(url, body:payload, headers: { 'Accept':'application/json', 'content-type': 'application/json' }) .then((value) => jsonDecode(value.body)); if(response['token'] != ''){ return true; } } catch(e){ errorMsg = e.toString(); notifyListeners(); return false; } return false; }
On successful authentication, it doesn't redirect to new screen as intended. Am I missing something or my logic is flawed?
CodePudding user response:
await
is meant to interrupt the process flow until the async
method has finished. then
however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.
In your code :
The issue is about your login
method. You used an await
with a then
, you don't need to use both at the same time.
Future<bool> login() async {
try{
var payload = jsonEncode({
'email': usrname,
'password': pswd
});
Map<String,dynamic> response = await fetch.post(url, body:payload, headers: {
'Accept':'application/json',
'content-type': 'application/json'
});
var decodedResponse = jsonDecode(response.body);
if(decodedResponse['token'] != ''){
return true;
}
}
catch(e){
errorMsg = e.toString();
notifyListeners();
return false;
}
return false;
}
You can find more examples in SO issues :