Search code examples
jsonflutterdio

How to access data in dio response - _JsonMap


I am making a request with dio

final Dio dio = new Dio();
return dio.post(api, data: data);
.then((response) {
  print(response.data.runtimeType);
  print(response.data);
  print(response.data.token);
}

The response data is printed, and the type is _JsonMap

When I want to print response.data.token I get this error

Error: NoSuchMethodError: 'token'

How do I access the token value? Thank you


Solution

  • I'm not sure if your syntax is right as according to the docs the response format should be a Response object using which you can get the data and headers.

    Not sure why it's JsonMap but you are accessing the response wrong since you have not deserialized it you should do this.

    final Dio dio = new Dio();
    
    return dio.post(api, data: data).then((response) {
      print(response.data.runtimeType);
      print(response.data);
      print(response.data['token']);
    }
    

    If such a key exists in the response, it'll print.