Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIO response decode issue

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 paring

{
"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

like image 425
Rahul Devanavar Avatar asked Jan 25 '19 13:01

Rahul Devanavar


People also ask

What is Dio in API?

A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

What is Dio client?

What is Dio? Dio is a powerful HTTP client for Dart. It has support for interceptors, global configuration, FormData , request cancellation, file downloading, and timeout, among others.

What is JSON decode in flutter?

jsonDecode function Null safetyParses the string and returns the resulting Json object. The optional reviver function is called once for each object or list property that has been parsed during decoding.


2 Answers

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);
like image 183
shadowsheep Avatar answered Oct 25 '22 19:10

shadowsheep


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();
like image 35
SHISHIR Avatar answered Oct 25 '22 17:10

SHISHIR