22

I am using Dio for making the HTTP request

  var dio = Dio();
    var response =
        await dio.get(URL);
    final responseBody = json.decode(response.data);

    final statusCode = response.statusCode;

    if (statusCode != 200 || responseBody == null) {
      print("status code:$statusCode");
      throw new ServerExceptionHandler(
          "An error ocurred : [Status Code : $statusCode]", statusCode);
    }

A response I am parsing

{
"x_id": "home"
}

but json.decode(response.data) is throwing the exception.

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

The Strange thing is when I replace Dio with http.get(url) then json.decode(response.body) works perfectly with same response

5
  • Look if this could help. Jan 25, 2019 at 13:41
  • tried not working Jan 25, 2019 at 13:53
  • Could you provide the url you are trying to get? Or at least could to get the json with postman e post it formatted on your question? Jan 25, 2019 at 13:55
  • updated the JSON response Jan 25, 2019 at 14:02
  • Okay got it. Wrote my answer. Jan 25, 2019 at 14:30

3 Answers 3

50

Your response data is already a Map so you could simply do that:

var response = await dio.get(_url);
var responseBody = response.data;
print(responseBody);

This is with explicit types:

Response<Map> response = await dio.get(_url);
Map responseBody = response.data;
print(responseBody);
3
  • 7
    yes, it's working, DIO returns decoded MAP. not required to decode Jan 25, 2019 at 14:36
  • @RahulDevanavar Yup. In this case (JSON body) it's so. For reference look at the response.dart repo code in toString. If you want you could also make this check too, but I guess that for a JSON body the response will always be a Map Jan 25, 2019 at 14:38
  • i had very similar case and that really worked for me
    – eko
    Apr 22, 2022 at 15:19
5

Follow this approach Take the response as String. Now you can decode it...

 Response<String> response = await DioUtils.getInstance().get(JSON_API);
 List responseJson = json.decode(response.data);
 return responseJson.map((m) => new User.fromJson(m)).toList();
0
    final dio = Dio(); 
    Response response = await dio.get("https://reqres.in/api/users?page=2");
    if (response.statusCode != 200) {
      throw Exception();
    } else {
      print("The response is that \n${response.data}\n"); 
       // no need to decode , when we use dio package , its response 
      // returns the String,dynamic
       return UserModel.fromMap(response.data); 
    }
1
  • You don't need to decode it. The dio package already decoded it from json to dart. Jan 6 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.