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.


You just need to add the authorization field into the request header:

var token = await getToken();

http.post(
    "$url",
    headers: {
        "Content-Type": "application/json",
        'Authorization': 'Bearer $token',
    },
    encoding: Encoding.getByName("utf-8"),
).then((response) {
    if (response.statusCode == 200) {
        print(json.decode(response.body));
        // Do the rest of job here
    }
});

This is the other possible solution for the problem. You have to wait response of getToken() function before continuing. You can accomplish it in two different ways. Either use "then" or "await".

Future<List<Theme>> getThemes() async {
    String url = 'http://10.0.2.2:3000/v1/api/theme';
    String token;
    Candidate().getToken().then((value) {
        token = value;

        final response = await http.get(url, headers: {
           'Content-Type': 'application/json',
           'Accept': 'application/json',
           'Authorization': 'Bearer $token',
        });
        print('Token : ${token}');
        print(response);

        if (response.statusCode == 200) {
           List themesList = jsonDecode(response.body);
           List<Theme> themes = [];
           for (var themeMap in themesList) {
              themes.add(Theme.fromJson(themeMap));
           }
           return themes;
         } else {
             throw Exception('Failed to load themes');
         }
    });
}

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"});