skip to Main Content

I use Dio to getting response, and this is my modeling classes:

import 'package:shoppingcenter/screens/homePage.dart';

class MALL {
  late final int id;
  late final String name;
  late final String images;

  MALL({required this.id, required this.name, required this.images});

  factory MALL.fromJson(Map<String, dynamic> data) {
    final id = data['id'];
    final name = data['name'];
    final images = data['images'];
    return MALL(id: id, name: name, images: images);
  }
}

class City {
  final List<MALL> malls;

  City({required this.malls});

  factory City.fromJson(Map<String, dynamic> data) {
    final mallData = data['malls'] as List<dynamic>?;
    final malls = mallData != null ? mallData.map((mallData) => MALL.fromJson(mallData)).toList() : <MALL>[];
    return City(malls: malls);
  }
}

I get this error when I try to use my classes:

Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'String'

My JSON is:

{
  "malls": [
    {
      "id": 1,
      "name": "city center",
      "images": "city.jpg"
    }
  ]
}

My response code:

Future<List<MALL>> get() async {
  final dio = Dio();
  var url = 'My URL';
  Response response = await dio.get(url);
  City api = City.fromJson(response.data);
  return api.malls;
}

What should I do?

2

Answers


  1. response.data is a String. You need to decode it to Map:

    City api = City.fromJson(jsonDecode(response.data));
    
    Login or Signup to reply.
  2. As I can see from your answers:

    Your API doesn’t return a JSON, it returns a HTML file. It tries to parse the html file with jsonDecode. Check your API with Postman, why it doesn’t return a response in JSON format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search