Good day. I am a flutter beginner and now do some simple pratice.
I want: Press a button and call login api, if api response is success then go to main page.
but I don’t know how to get callback result.
viewModel
Future<String> login(String account, String password) async {
try {
futureLogin = logon(account, password);
await futureLogin.then((value) {
print("key=${value.data.key}");//success print correct key
return value.data.key;
}).catchError((error) {
print("error=$error");
});
} catch (error) {}
return "";
}
Button click event
onPressed: () async {
var result = await viewModel.login(account, password);
print("result=${result}");//print ""
}
I think that I can simply use await keyword to get my api result but not works.
How to solve it.
Any help will be appreciate.
>Solution :
Try using async await :
Future<String> login(String account, String password) async {
try {
futureLogin = logon(account, password);
var value = await futureLogin;
return value.data.key;
} catch (error) {
return "";
}
}
or using .then function add return key after calling futureLogin
return await futureLogin.then(......);