I am getting the response from the api but after that json decoding error is coming up. It is showing that List is not type of string
import 'package:dio/dio.dart';
import 'package:dio_try/country_model.dart';
class DioClient {
final Dio dio = Dio();
static const baseUrl = 'some Url';
Future<CountryListModel> fetchPost() async {
try {
dio.options.headers['Content-Type'] = 'application/json';
dio.options.headers['fcm_token'] = 'test';
final response = await dio.post(baseUrl);
print(response.toString());
return CountryListModel.fromJson(response.data);
} on DioError catch (e) {
print(e.message e.error);
throw Exception(e.message e.error);
}
}
}
json response
[
{
"countryCode": "ALB",
"countryName": "ALBANIA",
"TypeId": "3",
"eligible": "Y"
},
]
Model Class
import 'dart:convert';
List<CountryListModel> countryListModelFromJson(String str) =>
List<CountryListModel>.from(
json.decode(str).map((x) => CountryListModel.fromJson(x)));
String countryListModelToJson(List<CountryListModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryListModel {
CountryListModel({
required this.countryCode,
required this.countryName,
required this.TypeId,
required this.eligible,
});
String countryCode;
String countryName;
String TypeId;
String eligible;
factory CountryListModel.fromJson(Map<String, dynamic> json) =>
CountryListModel(
countryCode: json["countryCode"],
countryName: json["countryName"],
TypeId: json["TypeId"],
eligible: json["eligible"],
);
Map<String, dynamic> toJson() => {
"countryCode": countryCode,
"countryName": countryName,
"TypeId": TypeId,
"eligible": eligible,
};
static List<CountryListModel> countryListModelFromJson(List<dynamic> list) =>
List<CountryListModel>.from(
list.map((x) => CountryListModel.fromJson(x)));
}
CodePudding user response:
ِYour api response is List
and your model class receive Map
so change your fetchPost
to this:
Future<List<CountryListModel>> fetchPost() async {
try {
dio.options.headers['Content-Type'] = 'application/json';
dio.options.headers['fcm_token'] = 'test';
final response = await dio.post(baseUrl);
print(response.toString());
return (response.data as List).map((e) => CountryListModel.fromJson(e)).toList();
} on DioError catch (e) {
print(e.message e.error);
throw Exception(e.message e.error);
}
}
CodePudding user response:
Change your function return type to List<CountryListModel>
and use the method countryListModelFromJson
in your CountryListModel
model.
Future<List<CountryListModel>> fetchPost() async {
try {
dio.options.headers['Content-Type'] = 'application/json';
dio.options.headers['fcm_token'] = 'test';
final response = await dio.post(baseUrl);
print(response.toString());
return CountryListModel.countryListModelFromJson(response.data);
} on DioError catch (e) {
print(e.message e.error);
throw Exception(e.message e.error);
}
}