i would like to perform a basic authentication with a simple token; how to perform this in flutter? which is the best way?

var response = await httpClient.post(url, 
    body: {'name': 'doodle', 'color': 'blue'});

is it sufficient to ad an authentication header, for example in this way ?

var response = await httpClient.post(
    url, 
    header:{ 
        'authorization' : 'bearer $token', 
        'content-type':'application/json'
    },
    body :{some body});

I'm using a JWT token type


Solution 1: Chaythanya Nair

You can use something like this.

var request = new http.Request('POST', Uri.parse(url));
request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json';
request.headers[HttpHeaders.AUTHORIZATION] = token;
request.body = json.encode(loginRequest.toMap());
await client.send(request).then((response) {
  response.stream.bytesToString().then((value) {
    print(value.toString());
    jsonResponse = value.toString();
    completer.complete(jsonResponse);
  });
}).catchError((error) {
    print(error.toString());
});


Solution 2: Ridha Rezzag

Pay attention to the word Bearer its must be Capitalized other ways it wont work, not sure whats the reason, but for flutter http calls make sure to capitalize that word like this

var response = await httpClient.post(
url, 
headers:{ 
    "Accept": "application/json",
    "Content-type": "application/json",
    "Authorization": "Bearer $token"
},
body :{some body});


Solution 3: my bytecode

I will prefer to use Dio library which has many features. File uploading is also super easy. So many things are handled by Dio itself.


Solution 4: Golden Lion

I used a dictionary of key/value pairs for the header information. I use the fromJson method of my dart class to serialize a list of object of type YourClass.

  import 'package:http/http.dart' as http

  String token = jwtToken;
  var client = http.Client();
  Map<String, String> headers = new HashMap();
  headers['Accept'] = 'application/json';
  headers['Content-Type'] = 'application/json';
  headers['Authorization'] = 'Bearer $token';

  var response = await client
      .post(url,
          headers: headers,
          body: json.encode(param),
          encoding: Encoding.getByName('utf-8'))
      .timeout(_TIMEOUT);

       if (response.statusCode == 200) {
           var parsed = json.decode(response.body).cast<Map<String, dynamic>>();
           list = parsed
                .map<YourClass>((json) => YourClass.fromJson(json))
        .toList();
       }