Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dio map flutter

I was using http and data was returned successfully, however when I used DIO, it shows me an error when returning data. I guess its because postFromJson takes a string, however it should take a map instead.

here’s the error at ‘json’ "_TypeError (type ‘List’ is not a subtype of type ‘String’)"

  Future<List<Post>?> getProducts() async {
    try {
      var response = await Dio().get('https://fakestoreapi.com/products');
      var json = response.data;

      if (response.statusCode == 200) {
        return postFromJson(json);
      } else {
        throw Exception("Error");
      }
    } catch (e) {
      throw (e);
    }
  }

This one is in the model file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<Post> postFromJson(String str) =>
    List<Post>.from(json.decode(str).map((x) => Post.fromJson(x)));

>Solution :

In this case (mostly with dio).. response.data already in JSON format (Map/List), so no need to decode it with json.decode(str)

Do this instead

List<Post> postFromJson(data) => List<Post>.from(data.map((x) => Post.fromJson(x)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading