Bearer token request http flutter
token
might not be set by the time it invokes http.get
. Change it to
String token = await Candidate().getToken(); final response = await http.get(url, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer $token', }); print('Token : ${token}'); print(response);
So that it is for sure set with right value.
Also you can use this method
String token = await Candidate().getToken();final response = http.get(url, headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});
The problem is that you assign your token in a different way.
When you do this await asyncFunction();
Dart will wait till it is complete. But, when you do like this asyncFunction().then((value) => print)
this tells Dart that it can continue executing your code, and when that asyncFunction is completed than print the value.
This is what happens on your case with
Candidate().getToken().then((value) { token = value; });
Here is a example, execute it on Dart Pad.