'How to set token in authorization header in flutter Dio post request

I want to set a token in the authorization header on my post request using Dio. I have tried to set the header using two options. And both don't work. The first way throws an error, the second, no data is sent to the server. What is the best way of adding an authorization token from shared preference and sending it as a header on a post request using Dio()

I am saving the token on SharedPreference when a user signs in and accesses it:

String token = "";

  @override
  void initState() {
    getToken();
  }

  void getToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString("token");
    setState((){});
  }

The first way am using to send the data with the header:

 Future<FormsModel> createEntry(
      String id,
      String formName,
      String dataContent,
      String dateCreated,
      String dateUpdated,
      String userLocation,
      String imeI,
      String updatedBy) async {
    String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
    Dio().options.headers["Authorization"] = "Bearer $token";
    await Dio().post(apiUrl, data: {
      "id": id,
      "formName": formName,
      "dataContent": dataContent,
      "dateCreated": dateCreated,
      "dateUpdated": dateUpdated,
      "userLocation": userLocation,
      "imeI": imeI,
      "updatedBy": updatedBy
    });

which throws an error

Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [302]

The second way am using to add the token to the headers:

Future<FormsModel> createEntry(
      String id,
      String formName,
      String dataContent,
      String dateCreated,
      String dateUpdated,
      String userLocation,
      String imeI,
      String updatedBy) async {
    String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
    await Dio().post(apiUrl, data: {
      "id": id,
      "formName": formName,
      "dataContent": dataContent,
      "dateCreated": dateCreated,
      "dateUpdated": dateUpdated,
      "userLocation": userLocation,
      "imeI": imeI,
      "updatedBy": updatedBy
    },
    options: Options( headers: {"authorization": "Bearer $token"},
    followRedirects: false,
    validateStatus: (status) { return status < 500; }));
  }

this way I don't get an error, but no data is sent to the server.



Solution 1:[1]

try like this

 String apiUrl = "http://10.0.2.2:8080/api/v1";

 final dio = Dio(
    BaseOptions(
       connectTimeout: 30000,
       baseUrl: apiUrl',
       responseType: ResponseType.json,
       contentType: ContentType.json.toString(),
  ));

 dio.options.headers["Authorization"] = "Bearer $token";
 await dio.post("/entry" , data: {
  "id": id,
  "formName": formName,
  "dataContent": dataContent,
  "dateCreated": dateCreated,
  "dateUpdated": dateUpdated,
  "userLocation": userLocation,
  "imeI": imeI,
  "updatedBy": updatedBy
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GJJ2019