Home > Net >  Unable to send header information with client.post
Unable to send header information with client.post

Time:07-16

I'm trying to pass along a bearer token and refresh token to an endpoint in Flutter but I'm getting errors no matter what I try. The api endpoint does work with Postman and returns a new token so the issue is with Flutter.


Future<List<PetsList>> fetchPets(http.Client client) async {

    var _headers = {
      'Content-Type': 'application/json',
      'token': singleton.token,
      'refreshToken': singleton.refreshToken,
    };

    var encodedHeader = json.encode(json.encode(_headers));

    final response = await client.post(
            Uri.parse(baseUrl   '/account/refreshtoken'),
            headers: encodedHeader);
    print("${response.body}");
};

This threw an error and stated that "The argument type 'String' can't be assigned to the parameter type 'Map<String, String>?'"

So I appended encodedHeader as Map<String, String> in the response

encodedHeader as Map<String, String>

but that then threw another error, "_CastError (type 'String' is not a subtype of type 'Map<String, String>' in type cast)"

Lastly, the response.body throws an error when I try to simply

print("${response.body}");

and states "Object reference not set to an instance of an object."

No matter what I've tried Flutter complains about this, I seem to be going in circles on this one and could use some help.

CodePudding user response:

The headers require a map<string, string> if you json encode it then it becomes a single string. Please remove the encode

Future<List<PetsList>> fetchPets(http.Client client) async {

    Map<String, String> _headers = {
      'Content-Type': 'application/json',
      'token': singleton.token,
      'refreshToken': singleton.refreshToken,
    };


    final response = await client.post(
            Uri.parse(baseUrl   '/account/refreshtoken'),
            headers: _headers);
 
};
  • Related