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
response.data
is aString
. You need to decode it toMap
: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.