List array of array in class model flutter - flutter

How to create class model in flutter if List Array of Array have 2 type data
Example
"value" : [["Water Melon", "Apple", 10, 23]]
#JsonSerializable()
class GetReportBodyData {
String type;
String title;
List<String> headers;
List<List<int>> value = new List<List<int>>();
GetReportBodyData({this.type, this.title, this.headers, this.value});
#override
String toString() {
return 'GetReportBodyData{type: $type, title: $title, header: $headers, value: $value}';
}
factory GetReportBodyData.fromJson(Map<String, dynamic> json) {
return GetReportBodyData(
type: json["type"],
title: json["title"],
headers: json["header"] != null ? List<String>.from(json["header"]) :[],
value: List<List<int>>.from(json["value"])
);
}
Map<String, dynamic>toJson() => {
"type": type,
"title": title,
"header": headers,
"value": value
};
}

class example {
List<List> value;
example({this.value});
example.fromJson(Map<String, dynamic> json) {
if (json['value'] != null) {
value = new List<List>();
json['value'].forEach((v) { value.add(new List.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.value != null) {
data['value'] = this.value.map((v) => v.toJson()).toList();
}
return data;
}
}
class Value {
Value({});
Value.fromJson(Map<String, dynamic> json) {
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
return data;
}

Related

Flutter error || Unhandled Exception: type 'SearchModel' is not a subtype of type 'List<SearchModel>' in type cast

I am making a search in ListView.builder where data is coming in JSON data
I am not getting the error what it wants to say the searchmodel is not a subtype of type List.
or should I go with another approach to work with search in listview.builder
here is my model
import 'dart:convert';
SearchModel searchModelFromJson(String str) =>
SearchModel.fromJson(json.decode(str));
String searchModelToJson(SearchModel data) => json.encode(data.toJson());
class SearchModel {
SearchModel({
required this.data,
required this.meta,
});
final List<Datum> data;
final Meta meta;
factory SearchModel.fromJson(Map<String, dynamic> json) => SearchModel(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class Datum {
Datum({
required this.id,
required this.attributes,
});
int? id;
Attributes? attributes;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes?.toJson(),
};
}
class Attributes {
Attributes({
required this.name,
required this.mobile,
required this.createdAt,
required this.updatedAt,
required this.shopEmail,
required this.shopUniqueId,
});
String? name;
String? mobile;
String? createdAt;
String? updatedAt;
String? shopEmail;
String? shopUniqueId;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
name: json["name"],
mobile: json["mobile"],
createdAt: json["createdAt"],
updatedAt: json["updatedAt"],
shopEmail: json["shopEmail"],
shopUniqueId: json["shopUniqueId"],
);
Map<String, dynamic> toJson() => {
"name": name,
"mobile": mobile,
"createdAt": createdAt,
"updatedAt": updatedAt,
"shopEmail": shopEmail,
"shopUniqueId": shopUniqueId,
};
}
class Meta {
Meta();
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
);
Map<String, dynamic> toJson() => {
};
}
here is my controller
class FetchSearch {
static Future<SearchModel> getUserList(String? query) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? jwt = prefs.getString('jwt');
var response = await http.get(
Uri.parse(searchUrl),
headers: <String,String> {
'Authorization' : 'Bearer $jwt'
},
);
if (response.statusCode == 200) {
print(response.statusCode);
var stringResponse = response.body;
print(stringResponse);
return SearchModel.fromJson(jsonDecode(stringResponse));
// Map<String,dynamic> search = json.decode(response.body);
// print(search);
// List<dynamic> data = map["data"];
// return search.map((json) => Attributes.fromJson(json)).toList();
}
else {
throw Exception();
}
and here is my variables and init function
int _currentPage = 0, _index = 0;
List<SearchModel> searchItem = [];
String query = '';
Future init() async {
final users = await FetchSearch.getUserList(query);
setState(() => this.searchItem = users as List<SearchModel>);
}

Serializing JSON response in Flutter

I would need assistance in serializing the below JSON Response. By far, I've managed to only extract the district property but cannot seem to understand how to go about with the properties of ward_no. The code for what I've done is below. Please note that I would like to serialize the JSON response in the same approach as on my code as I found it nearly impossible to wrap my head around the Serializing techniques suggested in the Official Documents.
The Response:
[
{
"district": "Kolkata", //I've only managed to extract this.
"ward_no": [
{
"ward": "6",
"grievance": [
{
"serial_number": "0001",
"name": "Siddhartha Chatterjee"
},
{
"serial_number": "0002",
"name": "Sajujjo Ghosh"
}
],
"general": [
{
"serial_number": "0003",
"name": "Dr. Partha Pratim Paul"
},
{
"serial_number": "0004",
"name": "Dr. Partha Pratim Paul"
}
],
"urgent": [
{
"serial_number": "0005",
"name": "Ritwick Banerjee"
},
{
"serial_number": "0006",
"name": "Soumadip Banerjee"
}
],
"services": [
{
"serial_number": "0007",
"name": "Tanajeet Biswas"
},
{
"serial_number": "0008",
"name": "Durba Chatterjee"
}
]
}
]
}
]
The code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Model {
final String district;
Model({required this.district});
}
class ModelClass with ChangeNotifier {
List<dynamic> _data = [];
List<dynamic> get data {
return [..._data];
}
Future<void> getData() async {
final url = Uri.http('192.168.0.6:3007', '/fetchData');
final response = await http.get(url);
print(response);
final extractedData = json.decode(response.body);
print(extractedData);
Map<String, Model> temp = {};
extractedData.forEach((value) {
temp.putIfAbsent(
value['_id'],
() =>
Model(district: value['district']));
});
print(temp);
_data = temp.values.toList();
print(_data);
}
}
P.S: I'm not looking to use boilerplate code generated by those JSON to Dart converter links
You can use this tools which will generate data class form the provided json
https://jsontodart.zariman.dev/
class Response {
String? district;
List<WardNo>? wardNo;
Response({this.district, this.wardNo});
Response.fromJson(Map<String, dynamic> json) {
this.district = json["district"];
this.wardNo = json["ward_no"]==null ? null : (json["ward_no"] as List).map((e)=>WardNo.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["district"] = this.district;
if(this.wardNo != null)
data["ward_no"] = this.wardNo?.map((e)=>e.toJson()).toList();
return data;
}
}
class WardNo {
String? ward;
List<Grievance>? grievance;
List<General>? general;
List<Urgent>? urgent;
List<Services>? services;
WardNo({this.ward, this.grievance, this.general, this.urgent, this.services});
WardNo.fromJson(Map<String, dynamic> json) {
this.ward = json["ward"];
this.grievance = json["grievance"]==null ? null : (json["grievance"] as List).map((e)=>Grievance.fromJson(e)).toList();
this.general = json["general"]==null ? null : (json["general"] as List).map((e)=>General.fromJson(e)).toList();
this.urgent = json["urgent"]==null ? null : (json["urgent"] as List).map((e)=>Urgent.fromJson(e)).toList();
this.services = json["services"]==null ? null : (json["services"] as List).map((e)=>Services.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["ward"] = this.ward;
if(this.grievance != null)
data["grievance"] = this.grievance?.map((e)=>e.toJson()).toList();
if(this.general != null)
data["general"] = this.general?.map((e)=>e.toJson()).toList();
if(this.urgent != null)
data["urgent"] = this.urgent?.map((e)=>e.toJson()).toList();
if(this.services != null)
data["services"] = this.services?.map((e)=>e.toJson()).toList();
return data;
}
}
class Services {
String? serialNumber;
String? name;
Services({this.serialNumber, this.name});
Services.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class Urgent {
String? serialNumber;
String? name;
Urgent({this.serialNumber, this.name});
Urgent.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class General {
String? serialNumber;
String? name;
General({this.serialNumber, this.name});
General.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class Grievance {
String? serialNumber;
String? name;
Grievance({this.serialNumber, this.name});
Grievance.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}

I am getting The method 'cast' was called on null while parsing json

I have following json in my API response :
{
"data": [{
"orderid": "123",
"item_names": [
"item1",
"item2",
"item3",
"item4"
]
}]
}
and i have following model class in dart :
class OrderListResponse {
List<OrderListItemModel> data;
OrderListResponse({this.data});
OrderListResponse.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<OrderListItemModel>();
json['data'].forEach((v) {
data.add(new OrderListItemModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class OrderListItemModel {
String id;
List<String> items;
OrderListItemModel({this.id,
this.items,
});
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
items = json['item_names'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['item_names'] = this.items;
return data;
}
}
When I will get data in API it gives me an error The method 'cast' was called on null. I am not getting why it throws this error. Any solution for this ?
I recommend you to use this website to convert your jsons
and so on, to fix you're code you need to change
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
items = json['item_names'].cast<String>();
}
to this
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['orderid'];
items = json["item_names"] == null? [] : List<String>.from(json["item_names"].map((x) => x))
}
You had a few mistakes in your code:
You are trying to cast a string to an array.
Your are trying to parse field id but the JSON field is orderid
Try this code:
import 'dart:convert';
void main() {
var js = '''{
"data": [{
"orderid": "123",
"item_names": [
"item1",
"item2",
"item3",
"item4"
]
}]
}''';
var orders = OrderListResponse.fromJson(json.decode(js));
for (var order in orders.data) {
print(order.id);
for (var item in order.items) {
print(item);
}
}
}
class OrderListResponse {
List<OrderListItemModel> data;
OrderListResponse({this.data});
OrderListResponse.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<OrderListItemModel>();
json['data'].forEach((v) {
data.add(new OrderListItemModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class OrderListItemModel {
String id;
List<String> items;
OrderListItemModel({this.id,
this.items,
});
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['orderid'];
items = List<String>.from(json["item_names"].map((x) => x));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['orderid'] = this.id;
data['item_names'] = this.items;
return data;
}
}

'List<dynamic>' is not a subtype of type 'List<options>'

I am getting error as 'List<dynamic>' is not a subtype of type 'List<options>'
Here is my code:
List<SampleModel> cartList = allStores.keys
// var allStores = response.data['data'];
// var cartList = allStores.keys
.map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map<Store>((store) => Store(
id: store['id'],
selected: false,
stid: store['stid'],
product: Products(
id: store['product']['id'],
type: store['product']['type_id'],
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
),
)
).toList(),
)
).toList();
Model:
class SampleModel {
String sname;
bool selected;
List<Store> storeList;
SampleModel({this.sname, this.selected, this.storeList});
SampleModel.fromJson(Map<String, dynamic> json) {
sname = json['sname'];
selected = json['selected'];
storeList = List<Store>.from(json["storeList"].map((x) => Store.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sname'] = this.sname;
data['selected'] = this.selected;
data['storeList'] = List<dynamic>.from(storeList.map((x) => x.toJson()));
return data;
}
}
class Store {
int id;
int stid;
Store({
this.id,
this.stid,
});
Store.fromJson(Map<String, dynamic> json) {
id = json['id'];
stid = json['cart_id'];
selected = json['selected'];
quantity = json['quantity'];
product = Products.fromJson(json["product"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['cart_id'] = this.stid;
data['product'] = product.toJson();
return data;
}
}
class Products {
int id;
String name;
List<Options> options;
Products({
this.id,
this.name,
this.options,
});
Products.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
type = json['type'];
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map((x) => Options.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['options'] = options == null
? null
: List<dynamic>.from(options.map((x) => x.toJson()));
return data;
}
}
}
class Options {
int id;
String name;
Options({
this.id,
this.name,
});
Options.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Here is my sample json
{
"sta1": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}],
"sta2": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}]
}
Everything works fine but options is not mapping, it shows error as
'List' is not a subtype of type 'List'
What am I missing here? Its an object and options is an array so I need to have it as a list in front end
everything i can able to loop but one thing options is not working
getting error in following line
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
I had a similar problem, I think that Flutter lost the reference of type of object, but I can fix using like this in your fromJson:
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map<Option>((x) => Options.fromJson(x.cast<String, dynamic>())));
}
Casting the map and using the cast in your map object.
I hope that can help you too.

Convert object to array in flutter

I need to convert object to array in flutter , Kindly find the json
{
"billing": [
{
"id": 1,
"add_id": 23
}
],
"shipping": [
{
"id": 2,
"add_id": 345
},
{
"id": 3,
"add_id": 345
}
]
}
I need to convert into array and map to model in flutter , how to do it
Use the following code to convert your JSON to a class object, the fromJson function convert JSON to object, and the toJson function convert the object to json.
class YourClassName {
List<Billing> billing;
List<Shipping> shipping;
YourClassName({this.billing, this.shipping});
YourClassName.fromJson(Map<String, dynamic> json) {
if (json['billing'] != null) {
billing = new List<Billing>();
json['billing'].forEach((v) {
billing.add(new Billing.fromJson(v));
});
}
if (json['shipping'] != null) {
shipping = new List<Shipping>();
json['shipping'].forEach((v) {
shipping.add(new Shipping.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.billing != null) {
data['billing'] = this.billing.map((v) => v.toJson()).toList();
}
if (this.shipping != null) {
data['shipping'] = this.shipping.map((v) => v.toJson()).toList();
}
return data;
}
}
class Billing {
int id;
int addId;
Billing({this.id, this.addId});
Billing.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}
class Shipping {
int id;
int addId;
Shipping({this.id, this.addId});
Shipping.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}