type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' Flutter - flutter

I need help on the following error type 'List' is not a subtype of type 'Map<String, dynamic>'
I tried every possible solution but I still cannot be able to solve it.
Future<List<Autogenerated>?> signInData() async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Charset": 'utf-8',
"Authorization": "Bearer $token",
},
));
print("data is here");
print(json.encode(response.data));
print(response.statusCode);
if (response.statusCode == 200) {
print("decoded");
// return List<Autogenerated>.from(
// response.data.map((i) => Autogenerated.fromJson(i)));
//return Autogenerated.fromJson(jsonDecode(json.encode(response.data)));
return (response.data as List)
.map((e) => Autogenerated.fromJson(e))
.toList();
} else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print(e);
}
}
I am getting error in the following line:
return (response.data as List)
.map((e) => Autogenerated.fromJson(e))
.toList();
My model class below
class Autogenerated {
int? id;
int? sourceId;
int? serviceId;
int? categoryId;
String? category;
String? description;
int? serviceResponsePropertyId;
int? mappingId;
bool? isVisible;
int? packageRequestId;
int? sortOrder;
Value? value;
Autogenerated(
{this.id,
this.sourceId,
this.serviceId,
this.categoryId,
this.category,
this.description,
this.serviceResponsePropertyId,
this.mappingId,
this.isVisible,
this.packageRequestId,
this.sortOrder,
this.value});
Autogenerated.fromJson(Map<String, dynamic> json) {
id = json['Id'];
sourceId = json['SourceId'];
serviceId = json['ServiceId'];
categoryId = json['CategoryId'];
category = json['Category'];
description = json['Description'];
serviceResponsePropertyId = json['ServiceResponsePropertyId'];
mappingId = json['MappingId'];
isVisible = json['IsVisible'];
packageRequestId = json['PackageRequestId'];
sortOrder = json['SortOrder'];
value = json['Value'] != null ? new Value.fromJson(json['Value']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Id'] = this.id;
data['SourceId'] = this.sourceId;
data['ServiceId'] = this.serviceId;
data['CategoryId'] = this.categoryId;
data['Category'] = this.category;
data['Description'] = this.description;
data['ServiceResponsePropertyId'] = this.serviceResponsePropertyId;
data['MappingId'] = this.mappingId;
data['IsVisible'] = this.isVisible;
data['PackageRequestId'] = this.packageRequestId;
data['SortOrder'] = this.sortOrder;
if (this.value != null) {
data['Value'] = this.value!.toJson();
}
return data;
}
}
class Value {
String? make;
String? type;
String? model;
int? year;
String? body;
String? driveType;
String? fueType;
Value(
{this.make,
this.type,
this.model,
this.year,
this.body,
this.driveType,
this.fueType});
Value.fromJson(Map<String, dynamic> json) {
make = json['make'];
type = json['type'];
model = json['model'];
year = json['year'];
body = json['body'];
driveType = json['drive_type'];
fueType = json['fue_type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['make'] = this.make;
data['type'] = this.type;
data['model'] = this.model;
data['year'] = this.year;
data['body'] = this.body;
data['drive_type'] = this.driveType;
data['fue_type'] = this.fueType;
return data;
}
}
My response from API(It's long, I just shorten it)
[
{
"Id": 0,
"SourceId": 0,
"ServiceId": 11,
"CategoryId": 5,
"Category": "Valuation",
"Description": "AdjustedValues",
"Value": [],
"ServiceResponsePropertyId": 474,
"MappingId": 0,
"IsVisible": true,
"PackageRequestId": 13853506,
"SortOrder": 1
},
{
"Id": 0,
"SourceId": 0,
"ServiceId": 11,
"CategoryId": 1,
"Category": "General",
"Description": "ServiceStatus",
"Value": {
"StatusCode": 1,
"StatusDescription": "Ok",
"StatusDetail": "",
"RestServiceStatus": null,
"ServiceResource": null
},
"ServiceResponsePropertyId": 475,
"MappingId": 0,
"IsVisible": false,
"PackageRequestId": 13853506,
"SortOrder": 1
},
{
"Id": 0,
"SourceId": 0,
"ServiceId": 6,
"CategoryId": 1,
"Category": "General",
"Description": "CarId",
"Value": 120354,
"ServiceResponsePropertyId": 100,
"MappingId": 0,
"IsVisible": false,
"PackageRequestId": 13853506,
"SortOrder": 1
},
{
"Id": 0,
"SourceId": 0,
"ServiceId": 6,
"CategoryId": 1,
"Category": "General",
"Description": "Year",
"Value": 2017,
"ServiceResponsePropertyId": 103,
"MappingId": 0,
"IsVisible": true,
"PackageRequestId": 13853506,
"SortOrder": 6
},
{
"Id": 0,
"SourceId": 0,
"ServiceId": 6,
"CategoryId": 1,
"Category": "General",
"Description": "Full Model Description",
"Value": "2017 AUDI A3 Sedan 1.0T FSI S tronic [2016-2017]",
"ServiceResponsePropertyId": 104,
"MappingId": 0,
"IsVisible": false,
"PackageRequestId": 13853506,
"SortOrder": 1
},
I cannot display data in lisview and I think it is because of this error. Please can you check there and please assist. Thank you in advance.

The error probably has been mis-attributed to the method Autogenerated.fromJson.
Problem
The method Value.fromJson() expects a Map<String, dynamic>:
Value.fromJson(Map<String, dynamic> json).
But the response.data shows that Value can be many things:
a List: "Value": []
a String: "Value": "abc"
a Map: "Value": { ... }
a Int: "Value": 123
Note
The first Value item in your response.data is a List. Which explains why the code is complaining about expecting a Map but getting a List.
Solution
Value.fromJson(...) needs to be able to handle lists, Strings, Ints, Maps etc. Not only Maps.

Related

type '(dynamic) => Product' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

I am trying to consume data from an API. I used quicktype.io to create a model class to parse the JSON data. The JSON data contains nested maps.
Now I am getting an error
The error is [type '(dynamic) => Product' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform']
This is the code for API request;
Future<void> setSpecials(String restaurantId) async {
try {
final url = Uri.parse(
ENDPOINT + 'restaurant/specials?restaurantId=$restaurantId&page=0');
final response = await http.get(url);
print(response.statusCode);
if (response.statusCode == 200) {
final List<Product> specials = productFromJson(response.body);
_specialsList = specials;
}
print(_specialsList.length);
notifyListeners();
} catch (e) {
print(e.toString());
}}
This is the model
List<Product> productFromJson(String str) => List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
String productToJson(List<Product> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Product {
Product({
required this.id,
required this.name,
required this.image,
required this.description,
required this.isFavourite,
required this.dishes,
required this.diet,
});
String id;
String name;
String image;
String description;
bool isFavourite;
List<Dish> dishes;
String diet;
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json["_id"],
name: json["name"],
image: json["image"],
description: json["description"],
isFavourite: json["isFavourite"],
dishes: List<Dish>.from(json["dishes"].map((x) => Dish.fromJson(x))),
diet: json["diet"] == null ? null : json["diet"],
);
Map<String, dynamic> toJson() => {
"_id": id,
"name": name,
"image": image,
"description": description,
"isFavourite": isFavourite,
"dishes": List<dynamic>.from(dishes.map((x) => x.toJson())),
"diet": diet == null ? null : diet,
};
}
class Dish {
Dish({
required this.name,
required this.price,
required this.offerIds,
required this.id,
});
String name;
double price;
List<dynamic> offerIds;
String id;
factory Dish.fromJson(Map<String, dynamic> json) => Dish(
name: json["name"],
price: double.parse(json["price"].toString()),
offerIds: List<dynamic>.from(json["offerIds"].map((x) => x)),
id: json["_id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"price": price,
"offerIds": List<dynamic>.from(offerIds.map((x) => x)),
"_id": id,
};
}
The JSON data is
[
{
"_id": "60edb147d91f7820c80585c9",
"name": "Chicken Biriyani",
"image": "localhost:3031\\images\\1626190484369-chicken-Biryani.jpg",
"description": "Chicken, Motton",
"isFavourite": false,
"dishes": [
{
"name": "Full",
"price": 200,
"offerIds": [],
"_id": "610e1cd618319924b45ef9cd"
},
{
"name": "Half",
"price": 150,
"offerIds": [],
"_id": "610e1cd618319924b45ef9ce"
},
{
"name": "Quarter",
"price": 100,
"offerIds": [],
"_id": "610e1cd618319924b45ef9cf"
}
]
},
{
"_id": "610cb83c231052429899df76",
"name": "Shavrma",
"image": "157.245.96.189:3031/images/1632371901688-IMG-20210922-WA0123.jpg",
"description": "Chicken Shavrma",
"diet": "Veg",
"isFavourite": false,
"dishes": [
{
"name": "Plate",
"price": 80,
"offerIds": [],
"_id": "610cb83c231052429899df77"
},
{
"name": "Roll",
"price": 60,
"offerIds": [],
"_id": "610cb83c231052429899df78"
}
]
}
]

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic> While working on a Todo App

I am trying to get data from a local API into my project, i am facing the following problem:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
// To parse this JSON data, do
//
// final toDo = toDoFromJson(jsonString);
import 'dart:convert';
import 'package:http/http.dart' as http;
ToDo toDoFromJson(String str) => ToDo.fromJson(json.decode(str));
String toDoToJson(ToDo data) => json.encode(data.toJson());
class ToDo {
ToDo({
required this.id,
required this.img,
required this.name,
required this.title,
required this.done,
required this.note,
required this.priority,
required this.dueDate,
required this.taskOwner,
required this.studentId,
required this.createdAt,
required this.updatedAt,
});
int id;
String img;
String name;
String title;
int done;
String note;
String priority;
String dueDate;
int taskOwner;
String studentId;
String createdAt;
String updatedAt;
factory ToDo.fromJson(Map<String, dynamic> json) => ToDo(
id: json["id"],
img: json["img"],
name: json["name"],
title: json["title"],
done: json["done"],
note: json["note"],
priority: json["priority"],
dueDate: json["due_date"],
taskOwner: json["TaskOwner"],
studentId: json["studentId"],
createdAt: json["createdAt"],
updatedAt: json["updatedAt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
"name": name,
"title": title,
"done": done,
"note": note,
"priority": priority,
"due_date": dueDate,
"TaskOwner": taskOwner,
"studentId": studentId,
"createdAt": createdAt,
"updatedAt": updatedAt,
};
}
Future<List<ToDo>> fetchTodos() async {
final response =
await http.get(Uri.parse('http://localhost:3000/task/all/1'));
if (response.statusCode == 200) {
final List<ToDo> todo = toDoFromJson(response.body) as List<ToDo>;
print(todo);
return todo;
} else {
print("nothing found");
return [];
}
}
Json from API is as below:
{
"id": 1,
"img": "assets/images/user/user1.jpg",
"name": "task 1",
"title": "eee",
"done": 0,
"note": "eee",
"priority": "Normal",
"due_date": "2021-07-06T18:30:00.000Z",
"TaskOwner": 1,
"studentId": "2",
"createdAt": "2021-07-26T14:39:54.000Z",
"updatedAt": "2021-07-26T14:39:54.000Z"
},
{
"id": 2,
"img": "assets/images/user/user1.jpg",
"name": "task 2",
"title": "nnjn",
"done": 0,
"note": "2525",
"priority": "High",
"due_date": "2021-07-19T18:30:00.000Z",
"TaskOwner": 1,
"studentId": "7",
"createdAt": "2021-07-27T15:05:31.000Z",
"updatedAt": "2021-07-27T15:05:31.000Z"
},
{
"id": 3,
"img": "assets/images/user/user1.jpg",
"name": "task 3",
"title": "5255",
"done": 0,
"note": "55",
"priority": "Normal",
"due_date": "2021-07-21T18:30:00.000Z",
"TaskOwner": 1,
"studentId": "7",
"createdAt": "2021-07-27T15:05:48.000Z",
"updatedAt": "2021-07-27T15:05:48.000Z"
},
{
"id": 4,
"img": "assets/images/user/user1.jpg",
"name": "task 4",
"title": "kaam kro",
"done": 0,
"note": "test note",
"priority": "Normal",
"due_date": "2021-07-21T18:30:00.000Z",
"TaskOwner": 1,
"studentId": "2",
"createdAt": "2021-08-04T14:45:47.000Z",
"updatedAt": "2021-08-04T14:45:47.000Z"
},
The method you are using to parse todos will return a ToDo object casted to a List<ToDo> which will cause an exception!
What you have to do is converting every single map in json to ToDo and then create a List from them.
Here is what you need to do:
replace this line
final List<ToDo> todo = toDoFromJson(response.body) as List<ToDo>;
with this:
final List<ToDo> todo = List<ToDo>.from(response.body.map((x) => toDoFromJson(x)))
fixed this by adding for loop to the Future function, refer to the code below -
Future<List<ToDo>> fetchTodos() async {
List<ToDo> todos = [];
final response =
await http.get(Uri.parse('https://dhulltransport.com:20625/task/all/1'));
if (response.statusCode == 200) {
var jsonList = jsonDecode(response.body);
for (var t in jsonList) {
todos.add(ToDo.fromJson(t));
}
print(todos.length);
return todos;
} else {
return [];
}
}

How to fix type 'List<dynamic>' is not a subtype of type 'String'

Currently I am getting this kind of issue from my code. I was trying to solved this problem continuously. But could not fund the solution of this problem.
Json Codes
{
"id": 22,
"client_need_id": 46,
"clientNeed": {
"id": 46,
"client_id": 29,
"perpose": "Pooja",
"details": "Test",
"when": "2020-08-28 20:11",
"for": null,
"accepted_by": 10,
"name": "Sfgdsa",
"mobile": "567896789",
"email": "sdnsd#asd.com",
"org_name": "Buii",
"address": "Tata",
"city": "Kolkata",
"state": "West Bengal",
"pincode": "789009",
"country": "India",
"latitude": null,
"longitude": null,
"client_ip": null,
"device": null,
"created_at": "2020-08-23T14:40:06.000000Z",
"updated_at": "2020-09-02T18:07:40.000000Z"
},
"quote_details": null,
"quote_amount": null,
"isCalled": 0,
"isChecked": 0,
"isAccept": 1,
"isGoing": 0,
"checkIn": "2020-09-03 02:00:00",
"checkOut": "2020-09-03 02:00:15",
"pandit_id": 10,
"pandit": {
"id": 10,
"name": "Ajay Roy",
"mobile": "8013138886",
"sms_token": null,
"mobile_verified_at": null,
"email": "ajay#abc.com",
"email_token": null,
"email_verified_at": null,
"password": "5f4dcc3b5aa765d61d8327deb882cf99",
"remember_token": null,
"avatar": null,
"address": "dum dum cantonment",
"city": "Kolkata",
"state": "West Bengal",
"country": "India",
"pincode": 700028,
"location_id": null,
"travelled": null,
"adharcard": "34567890",
"pancard": "ATD8994568",
"specialisation": "Vastushastri",
"services": [
"Artrology",
"Numerology"
],
"min_charge": "500",
"max_charge": "1000",
"online_charge": "700",
"qualification": "Test1",
"experience": "12 Years",
"language": "Bengali",
"active": "0",
"varify": "1",
"payment_mode": "{\"bank_name\":\"HDFC Bank\",\"bank_address\":\"Dum Dum Cant\",\"ifsc_code\":\"HDFC098765\",\"account_no\":\"987654654678\",\"account_holder\":\"Abit Roy\"}",
"created_at": "2020-08-31T19:03:56.000000Z",
"updated_at": "2020-09-16T12:40:54.000000Z"
},
"visits": [
{
"id": 70,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": "2020-09-03 02:00:00",
"checkOut": null,
"created_at": "2020-09-02T20:30:00.000000Z",
"updated_at": "2020-09-02T20:30:00.000000Z"
},
{
"id": 71,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": null,
"checkOut": "2020-09-03 02:00:15",
"created_at": "2020-09-02T20:30:15.000000Z",
"updated_at": "2020-09-02T20:30:15.000000Z"
}
]
}
Lead Model
import 'dart:convert';
import 'package:PandeetApp/models/client_need.dart';
import 'package:PandeetApp/models/pandit.dart';
import 'package:PandeetApp/models/visit.dart';
import 'package:PandeetApp/services/lead.dart';
class Lead extends LeadService {
int id;
int clientNeedId;
ClientNeed clientNeed;
String quoteDetails;
String quoteAmount;
int isCalled;
int isChecked;
int isAccept;
int isGoing;
String checkIn;
String checkOut;
int panditId;
Pandit pandit;
List<Visit> visits;
Lead({
this.id,
this.clientNeedId,
this.clientNeed,
this.quoteDetails,
this.quoteAmount,
this.isCalled,
this.isChecked,
this.isAccept,
this.isGoing,
this.checkIn,
this.checkOut,
this.panditId,
this.pandit,
this.visits,
});
Future<List<Lead>> fetchLeads() async {
var datas = await super.fetchDatas();
var dataList = json.decode(datas);
var leads = dataList.map((e) => Lead.fromJson(e)).toList();
return leads;
}
factory Lead.fromJson(Map<String, dynamic> json) {
List<Visit> visits = List<Visit>();
if (json['visits'] != null) {
json['visits'].forEach((v) {
visits.add(Visit.fromJson(v));
});
}
return Lead(
id: json['id'],
clientNeedId: json['client_need_id'],
clientNeed: json['clientNeed'] != null
? ClientNeed.fromJson(json['clientNeed'])
: ClientNeed(),
quoteDetails: json['quote_details'],
quoteAmount: json['quote_amount'],
isCalled: json['isCalled'],
isChecked: json['isChecked'],
isAccept: json['isAccept'],
isGoing: json['isGoing'],
checkIn: json['checkIn'],
checkOut: json['checkOut'],
panditId: json['pandit_id'],
pandit:
json['pandit'] != null ? Pandit.fromJson(json['pandit']) : Pandit(),
visits: visits,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
if (this.clientNeed != null) {
data['clientNeed'] = this.clientNeed.toJson();
}
data['quote_details'] = this.quoteDetails;
data['quote_amount'] = this.quoteAmount;
data['isCalled'] = this.isCalled;
data['isChecked'] = this.isChecked;
data['isAccept'] = this.isAccept;
data['isGoing'] = this.isGoing;
data['checkIn'] = this.checkIn;
data['checkOut'] = this.checkOut;
if (this.pandit != null) {
data['pandit'] = this.pandit.toJson();
}
if (this.visits != null) {
data['visits'] = this.visits.map((v) => v.toJson()).toList();
}
return data;
}
}
Screen Part
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List leads = snapshot.data;
// print(leads.length); // Data Not Getting Here
if (leads.length > 0) {
return dataList(leads);
} else {
return Container(
padding: EdgeInsets.only(top: 200),
child: Text("You have no clients"),
);
}
} else if (snapshot.hasError) {
print(snapshot.error);
return Text("Server is Down now. Try again later");
}
return Container(
padding: EdgeInsets.only(top: 200),
child: CircularProgressIndicator(
backgroundColor: Colors.redAccent,
),
);
},
);
I think here have the problem. I was completed my project but this type of problem ruin my project. I could not understand where i am wrong for this problem. Exact line number could not found. Give just hint but where exactly problem not understandable. Please help me as soon as possible.
Don't cast the snapshot data as List instead use var. Try the print results before error and proceed further
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var leads = snapshot.data; // use var instead of List
// try this in your case it is received as String
print(leads.runtimeType.toString())
// if it is string convert to List.
var leadsJson = jsonDecode(leads)

How to parse list from a list of data json in flutter

I have an issue parsing my jsonData in flutter. This is my json.
{
"status": "success",
"data": [
{
"id": "02ab1ef0-6fa9-11ea-ba0f-b1d475e9cef4",
"policy_name": "Third Party Insurance",
"description": "This is Third Party Insurance",
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 21:30:27",
"updated_at": "2020-03-26 21:30:27",
"insurance_policy_type": [
{
"id": "3c674550-6faa-11ea-b97c-9d7c2598dab0",
"insurance_policy_id": "02ab1ef0-6fa9-11ea-ba0f-b1d475e9cef4",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Third Party - Grade A",
"description": "Third Party - Grade A. Third Party - Grade A. Third Party - Grade A",
"benefit": "Benefit of Third Party - Grade A. This is going to be a long text",
"amount": 5000,
"commission": 300,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 21:39:13",
"updated_at": "2020-03-26 21:39:13"
},
{
"id": "4ec7a4a0-6faa-11ea-9739-77f0ed3fc12c",
"insurance_policy_id": "02ab1ef0-6fa9-11ea-ba0f-b1d475e9cef4",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Third Party - Grade B",
"description": "Third Party - Grade B. Third Party - Grade B. Third Party - Grade B",
"benefit": "Benefit of Third Party - Grade B. This is going to be a long text",
"amount": 8000,
"commission": 500,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 21:39:44",
"updated_at": "2020-03-26 21:39:44"
}
]
},
{
"id": "10e31df0-6fa9-11ea-962f-e5df8d00bea3",
"policy_name": "Personal Accident Insurance",
"description": "This is Personal Accident Insurance",
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 21:30:51",
"updated_at": "2020-03-26 21:30:51",
"insurance_policy_type": [
{
"id": "aaf3ef10-6fb2-11ea-8c17-8de2cd67bf64",
"insurance_policy_id": "10e31df0-6fa9-11ea-962f-e5df8d00bea3",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Personal Accident - Grade A",
"description": "Personal Accident - Grade A. Personal Accident - Grade A. Personal Accident - Grade A",
"benefit": "Benefit of Personal Accident - Grade A. This is going to be a long text",
"amount": 4000,
"commission": 500,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:39:35",
"updated_at": "2020-03-26 22:39:35"
},
{
"id": "b4835d00-6fb2-11ea-a48f-c3481acd8970",
"insurance_policy_id": "10e31df0-6fa9-11ea-962f-e5df8d00bea3",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Personal Accident - Grade B",
"description": "Personal Accident - Grade B. Personal Accident - Grade B. Personal Accident - Grade B",
"benefit": "Benefit of Personal Accident - Grade B. This is going to be a long text",
"amount": 4000,
"commission": 500,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:39:51",
"updated_at": "2020-03-26 22:39:51"
},
{
"id": "c6d84e60-6fb2-11ea-a773-497e66c9ab29",
"insurance_policy_id": "10e31df0-6fa9-11ea-962f-e5df8d00bea3",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Personal Accident - Grade C",
"description": "Personal Accident - Grade C. Personal Accident - Grade C. Personal Accident - Grade C",
"benefit": "Benefit of Personal Accident - Grade C. This is going to be a long text",
"amount": 10000,
"commission": 1000,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:40:21",
"updated_at": "2020-03-26 22:40:21"
}
]
},
{
"id": "1a727fc0-6fa9-11ea-a43f-b52dc75efa00",
"policy_name": "Household Insurance",
"description": "This is Household Insurance",
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 21:31:07",
"updated_at": "2020-03-26 21:34:17",
"insurance_policy_type": [
{
"id": "016fa680-6fb3-11ea-93b7-3fdae3d5875a",
"insurance_policy_id": "1a727fc0-6fa9-11ea-a43f-b52dc75efa00",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Household Insurance - Grade D",
"description": "Household Insurance - Grade D. Household Insurance - Grade D. Household Insurance - Grade D",
"benefit": "Benefit of Household Insurance - Grade D. This is going to be a long text",
"amount": 9000,
"commission": 1000,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:42:00",
"updated_at": "2020-03-26 22:42:00"
},
{
"id": "13a62720-6fb3-11ea-8842-ed9732bb7c86",
"insurance_policy_id": "1a727fc0-6fa9-11ea-a43f-b52dc75efa00",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Household Insurance - Grade K",
"description": "Household Insurance - Grade K. Household Insurance - Grade K. Household Insurance - Grade K",
"benefit": "Benefit of Household Insurance - Grade K. This is going to be a long text",
"amount": 7500,
"commission": 600,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:42:30",
"updated_at": "2020-03-26 22:42:30"
},
{
"id": "f4ceb490-6fb2-11ea-9b04-a1229a2e2128",
"insurance_policy_id": "1a727fc0-6fa9-11ea-a43f-b52dc75efa00",
"insurance_company_id": "07a53f10-6fa8-11ea-bb6d-89fb742a644e",
"policy_type_name": "Household Insurance - Grade C",
"description": "Household Insurance - Grade C. Household Insurance - Grade C. Household Insurance - Grade C",
"benefit": "Benefit of Household Insurance - Grade C. This is going to be a long text",
"amount": 9000,
"commission": 1000,
"status": 1,
"deleted_at": null,
"created_at": "2020-03-26 22:41:39",
"updated_at": "2020-03-26 22:41:39"
}
]
}
]
}
I have generated a model for this data which works perfectly.
class Insurance {
String status;
List<Data> data;
Insurance({this.status, this.data});
Insurance.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String id;
String policyName;
String description;
int status;
var deletedAt;
String createdAt;
String updatedAt;
List<InsurancePolicyType> insurancePolicyType;
Data(
{this.id,
this.policyName,
this.description,
this.status,
this.deletedAt,
this.createdAt,
this.updatedAt,
this.insurancePolicyType});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
policyName = json['policy_name'];
description = json['description'];
status = json['status'];
deletedAt = json['deleted_at'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
if (json['insurance_policy_type'] != null) {
insurancePolicyType = new List<InsurancePolicyType>();
json['insurance_policy_type'].forEach((v) {
insurancePolicyType.add(new InsurancePolicyType.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['policy_name'] = this.policyName;
data['description'] = this.description;
data['status'] = this.status;
data['deleted_at'] = this.deletedAt;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.insurancePolicyType != null) {
data['insurance_policy_type'] =
this.insurancePolicyType.map((v) => v.toJson()).toList();
}
return data;
}
}
class InsurancePolicyType {
String id;
String insurancePolicyId;
String insuranceCompanyId;
String policyTypeName;
String description;
String benefit;
int amount;
int commission;
int status;
Null deletedAt;
String createdAt;
String updatedAt;
InsurancePolicyType(
{this.id,
this.insurancePolicyId,
this.insuranceCompanyId,
this.policyTypeName,
this.description,
this.benefit,
this.amount,
this.commission,
this.status,
this.deletedAt,
this.createdAt,
this.updatedAt});
InsurancePolicyType.fromJson(Map<String, dynamic> json) {
id = json['id'];
insurancePolicyId = json['insurance_policy_id'];
insuranceCompanyId = json['insurance_company_id'];
policyTypeName = json['policy_type_name'];
description = json['description'];
benefit = json['benefit'];
amount = json['amount'];
commission = json['commission'];
status = json['status'];
deletedAt = json['deleted_at'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['insurance_policy_id'] = this.insurancePolicyId;
data['insurance_company_id'] = this.insuranceCompanyId;
data['policy_type_name'] = this.policyTypeName;
data['description'] = this.description;
data['benefit'] = this.benefit;
data['amount'] = this.amount;
data['commission'] = this.commission;
data['status'] = this.status;
data['deleted_at'] = this.deletedAt;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
Main.dart
List<InsurancePolicyType> insurancePolicyType;
List<Data> insuranceDataList = [];
...
insuranceDataList = List<Data>.from(
responseJson["data"].map((i) => Data.fromJson(i)));
for (var i = 0; i < insuranceDataList.length; i++) {
insurancePolicyType = List<InsurancePolicyType>.from(
responseJson["data"][i]["insurance_policy_type"].map((i) =>InsurancePolicyType.fromJson(i)));
So inside every index is another list which i need to save inside the InsurancePolicyType object. Thats the data am trying to fetch.
How do i fetch List<InsurancePolicyType> insurancePolicyType in my code? I need to fetch that list but i have not been able to.
Writing getter should be fine in this case
class Insurance {
String status;
List<Data> data;
List<InsurancePolicyType> get getAllInsurancePolicies {
List<InsurancePolicyType> fetchedList = List();
for (var d in data) {
fetchedList.addAll(d.insurancePolicyType);
}
return fetchedList;
}
Insurance({this.status, this.data});
Insurance.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
Without changing anything in your models. The following solution will work:
List<InsurancePolicyType> insurancePolicyType;
List<Data> insuranceDataList;
insuranceDataList =
List<Data>.from(responseJson["data"].map((i) => Data.fromJson(i)));
insurancePolicyType = insuranceDataList
.map((insuranceData) => insuranceData.insurancePolicyType)
.expand((type) => type)
.toList();
Once you have deserialized the json data, it is easier to use the resultant objects to retrieve the insurance policy types you want.
This solution gets all the policy types from each Data object and then flattens that list to get the desired list of policy types.
Please check out this model class and directly use it. Firstly you get the complete object using this call :
final insurance = insuranceFromJson(jsonString);
Later extract the list of data from the object using the
following:
I will show you step by step:
List<YourObejct(I have used the Datum as a name)> data =List();
later pass the response.body to the below method:
final insurance = insuranceFromJson(response.body);
Here you get your complete Insurance object just extract the data Object using the following:
data = insurance.data;
and Later Do your desired Stuff, I have mentioned the model class below depending on your JSON you provided.
// To parse this JSON data, do
//
// final insurance = insuranceFromJson(jsonString);
import 'dart:convert';
Insurance insuranceFromJson(String str) => Insurance.fromJson(json.decode(str));
String insuranceToJson(Insurance data) => json.encode(data.toJson());
class Insurance {
String status;
List<Datum> data;
Insurance({
this.status,
this.data,
});
factory Insurance.fromJson(Map<String, dynamic> json) => Insurance(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String policyName;
String description;
int status;
dynamic deletedAt;
DateTime createdAt;
DateTime updatedAt;
List<InsurancePolicyType> insurancePolicyType;
Datum({
this.id,
this.policyName,
this.description,
this.status,
this.deletedAt,
this.createdAt,
this.updatedAt,
this.insurancePolicyType,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
policyName: json["policy_name"],
description: json["description"],
status: json["status"],
deletedAt: json["deleted_at"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
insurancePolicyType: List<InsurancePolicyType>.from(json["insurance_policy_type"].map((x) => InsurancePolicyType.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"policy_name": policyName,
"description": description,
"status": status,
"deleted_at": deletedAt,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"insurance_policy_type": List<dynamic>.from(insurancePolicyType.map((x) => x.toJson())),
};
}
class InsurancePolicyType {
String id;
String insurancePolicyId;
String insuranceCompanyId;
String policyTypeName;
String description;
String benefit;
int amount;
int commission;
int status;
dynamic deletedAt;
DateTime createdAt;
DateTime updatedAt;
InsurancePolicyType({
this.id,
this.insurancePolicyId,
this.insuranceCompanyId,
this.policyTypeName,
this.description,
this.benefit,
this.amount,
this.commission,
this.status,
this.deletedAt,
this.createdAt,
this.updatedAt,
});
factory InsurancePolicyType.fromJson(Map<String, dynamic> json) => InsurancePolicyType(
id: json["id"],
insurancePolicyId: json["insurance_policy_id"],
insuranceCompanyId: json["insurance_company_id"],
policyTypeName: json["policy_type_name"],
description: json["description"],
benefit: json["benefit"],
amount: json["amount"],
commission: json["commission"],
status: json["status"],
deletedAt: json["deleted_at"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"insurance_policy_id": insurancePolicyId,
"insurance_company_id": insuranceCompanyId,
"policy_type_name": policyTypeName,
"description": description,
"benefit": benefit,
"amount": amount,
"commission": commission,
"status": status,
"deleted_at": deletedAt,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}

Flutter return array from response from server

in this part of my code await webApi.getKeywords(); return array which that can get from server, now when i try to return that i get error:
type 'List<dynamic>' is not a subtype of type 'String'
get data from server code:
Future<List<KeywordsResponse>> _getKeywords(BuildContext context) async {
try {
final webApi = Provider.of<WebApi>(context);
final response = await webApi.getKeywords();
List<KeywordsResponse> list = List();
if (response.statusCode == 200) {
list = (json.decode(response.body) as List)
.map((data) => new KeywordsResponse.fromJson(data))
.toList();
return list;
} else {
throw Exception('Failed to load photos');
}
} catch (error) {
print(error);
return null;
}
}
KeywordsResponse class:
#JsonSerializable(nullable: true)
class KeywordsResponse{
#JsonKey(name:'id')
final int id;
#JsonKey(name:'title')
final String title;
#JsonKey(name:'description')
final String description;
KeywordsResponse(this.id, this.title, this.description);
factory KeywordsResponse.fromJson(Map<String, dynamic> json) => _$KeywordsResponseFromJson(json);
Map<String, dynamic> toJson() => _$KeywordsResponseToJson(this);
}
return of response.body:
[
{
"id": 1,
"user_id": 1,
"title": "asdasdasd",
"description": "asdasdasd",
"type": "post",
"slug": "asdasdad",
"featured_images": {
"images": {
"300": "/uploads/post_images/2019/300_1573573784.png",
"600": "/uploads/post_images/2019/600_1573573784.png",
"900": "/uploads/post_images/2019/900_1573573784.png",
"original": "/uploads/post_images/2019/1573573784.png"
},
"thumbnail": "/uploads/post_images/2019/300_1573573784.png"
},
"lang": "fa",
"visit": 0,
"categories": [
{
"id": 1,
"title": "aaaaaaa",
"lang": "fa",
"parent": 0,
"pivot": {
"contents_id": 1,
"content_categories_id": 1
}
}
]
},
{
"id": 2,
"user_id": 1,
"title": "asdasdasd",
"description": "asdadasd",
"type": "post",
"slug": "asdasdasda",
"featured_images": {
"images": {
"300": "/uploads/post_images/2019/300_1573573846.png",
"600": "/uploads/post_images/2019/600_1573573846.png",
"900": "/uploads/post_images/2019/900_1573573846.png",
"original": "/uploads/post_images/2019/1573573846.png"
},
"thumbnail": "/uploads/post_images/2019/300_1573573846.png"
},
"lang": "fa",
"visit": 0,
"categories": [
{
"id": 2,
"title": "bbbbbbbb",
"lang": "fa",
"parent": 0,
"pivot": {
"contents_id": 2,
"content_categories_id": 2
}
}
]
}
]
problem is on this line of code:
json.decode(response.body)
Try this:
list = List<KeywordsResponse>.from(response.body.map((x) => KeywordsResponse.fromJson(x)));