in one of my ChangeNotifier, if have an authentificate method. This is a method, that gets an auth - token with a Future gettoken function and then sets the some values of the LoginController class.
When I call the .authentificate using Provider.of(), I think, I change the result of getToken from a Future<String> to a simple <String> (via .then(...)) and then try to evaluate wether the token was received or not. Unfortunately, the last thing that is printed is "API Authentification success" from the get getToken function and not Evaluating the token. What do I do wrong here?
class LoginController extends ChangeNotifier {
int pagenr = 0;
bool is_logged_in = false;
String token_string = "";
void change_page_nr(int item) {
pagenr = item;
notifyListeners();
}
void authenticate(String username,String password) {
getToken(username, password).then((String result){token_string = result;});
// Code seems to stop working here, at least nothing is printed or changed even though
// the token request exits without an error.
print("Evaluating the token");
if (token_string.length > 0) {
print("Logging in succesful!");
is_logged_in = true;
int pagenr = 1;
} else {
print("Logging in failed!");
is_logged_in = false;
int pagenr = 0;
}
notifyListeners();
}
with
Future<String> getToken(String username, String password) async {
print("TokenURL in api_connection.dart");
print(_tokenURL);
final http.Response response = await http.post(
Uri.parse(_tokenURL),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*'
},
body: jsonEncode(<String, String>{
'username': username,
'password': password
}
)
);
if (response.statusCode == 200) {
print("API Authentification successful!");
return json.decode(response.body)["token"];
} else {
print(json.decode(response.body).toString());
print("API Authentification failed");
return "";
}
}
CodePudding user response:
Change authenticate
function to asynchronous and await getToken
.
Future<void> authenticate(String username,String password) async {
final token_string = await getToken(username, password);
...
notifyListeners();
}