Home > Blockchain >  Dio map flutter
Dio map flutter

Time:07-24

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.

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

CodePudding user response:

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)));
  • Related