How to Send Bearer Token Request In Flutter ??

· 3 min read
How to Send Bearer Token Request In Flutter
How to Send Bearer Token Request In Flutter

In order to request a new access token, you need to use the post method along with form data and required Dio’s options content-type and headers. so in this article, we will walk through how to Send Bearer Token Request in flutter.

How to Send Bearer Token Request In Flutter ??

This kind of error generally occurs because of 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 a sure set with the right value.

Also, you can use this method as below:

String token = await Candidate().getToken();
final response = http.get(url,
        headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

When you do this await async function(); Dart will wait till it is complete.

But, when you do like this async function().then((value) => print) this tells Dart that it can continue executing your code, and when that async function is completed then print the value.

his is what happens in your case with

Candidate().getToken().then((value) {
      token = value;
    });

Here is an example, execute it on Dart Pad. https://gist.github.com/bmatheus91/b3aac14e941449bb18609f77a8a8f8ab

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

getProfile() async {
print(getToken());
var token = await getToken();
http.post(
      "$url",
      headers: {
        "Content-Type": "application/json",
        'Authorization': 'Bearer $token',
      },
      encoding: Encoding.getByName("utf-8"),
    ).then((response) {
      print(datafromurl);
      if (response.statusCode == 200) {
         print(json.decode(response.body));
      }
    });
}

Conclusion:

Thanks for being with us on a Flutter Journey !!!

Keep Learning !!! Keep Fluttering !!!

In this article, we learned how to send bearer token requests in flutter.

Drop us your valuable suggestion/feedback to serve you better.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply