This is the Response
{
"message": null,
"data": {
"items": [
{
"dealerId": 634,
"dealerName": "Test12",
"dealerCode": "dandasn123"
},
{
"dealerId": 36,
"dealerName": "Saurabh",
"dealerCode": "ASDF"
},
{
"dealerId": 38,
"dealerName": "Muskan",
"dealerCode": "ASDF"
},
{
"dealerId": 16,
"dealerName": "Nsj94",
"dealerCode": "ASDF1234"
}
]
},
"type": null
}
This is the Model which I have created using jsonToDart Plugin available in Android Studio
import 'Data.dart';
class DealerDetailsModel {
DealerDetailsModel({
this.message,
this.data,
this.type,
});
DealerDetailsModel.fromJson(dynamic json) {
message = json['message'];
data = json['data'] != null ? Data.fromJson(json['data']) : null;
type = json['type'];
}
dynamic message;
Data? data;
dynamic type;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['message'] = message;
if (data != null) {
map['data'] = data?.toJson();
}
map['type'] = type;
return map;
}
}
import 'Items.dart';
class Data {
Data({
this.items,
});
Data.fromJson(dynamic json) {
if (json['items'] != null) {
items = [];
json['items'].forEach((v) {
items?.add(Items.fromJson(v));
});
}
}
List<Items>? items;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (items != null) {
map['items'] = items?.map((v) => v.toJson()).toList();
}
return map;
}
}
class Items {
Items({
this.dealerId,
this.dealerName,
this.dealerCode,
});
Items.fromJson(dynamic json) {
dealerId = json['dealerId'];
dealerName = json['dealerName'];
dealerCode = json['dealerCode'];
}
int? dealerId;
String? dealerName;
String? dealerCode;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['dealerId'] = dealerId;
map['dealerName'] = dealerName;
map['dealerCode'] = dealerCode;
return map;
}
}
and this is the method that I have created to fetch dealer details, and here only I am facing the error where I have written getData as List
Future<List<DealerDetailsModel>> getDealerDetails() async {
var params = {'': ''};
if (isNetworkAvail) {
await apiBaseHelper.getAPICall(getDealerDetailsData, params).then(
(getData) async => {
dealerData = (getData as List)
.map((data) => DealerDetailsModel.fromJson(data))
.toList(),
},
);
}
return dealerData;
}
CodePudding user response:
Your issue is that you are expect a list from api response but it is a Map
. So you need to parse it like this. Change your getDealerDetails
to this:
Future<DealerDetailsModel?> getDealerDetails() async {
var params = {'': ''};
if (isNetworkAvail) {
var getData = await apiBaseHelper.getAPICall(getDealerDetailsData, params);
return DealerDetailsModel.fromJson(getData);
}
return null;
}
remember change your FutureBuilder's type to DealerDetailsModel?
instead of List<DealerDetailsModel>
.