I need to create a dart Model class for this complex json .Please any one help
{
"status": "1",
"list": {
"4": [
{
"id": "1289",
"t": "Mutton biriyani",
"p": "21",
"i": "1289_5305.jpg",
"v": "0"
},
{
"id": "1288",
"t": "Chicken biriyani",
"p": "14",
"i": "1288_5339.jpg",
"v": "0"
}
]
}
}
can any one help
you can create modal of every json using this website json-to-dart.
and after making some changes the modal for your jsong would be something like this
class Modal {
String? status;
List<FoodList>? foodList;
Modal({this.status, this.foodList});
Modal.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['list']["4"] != null) {
foodList = <FoodList>[];
json['list']["4"].forEach((v) {
foodList!.add(new FoodList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.foodList != null) {
data['list']["4"] = this.foodList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class FoodList {
String? id;
String? t;
String? p;
String? i;
String? v;
FoodList({this.id, this.t, this.p, this.i, this.v});
FoodList.fromJson(Map<String, dynamic> json) {
id = json['id'];
t = json['t'];
p = json['p'];
i = json['i'];
v = json['v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['t'] = this.t;
data['p'] = this.p;
data['i'] = this.i;
data['v'] = this.v;
return data;
}
}
Here is an example of a Dart Model class that could be used to parse the JSON you provided
class Model {
final String status;
final List list;
Model({this.status, this.list});
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
status: json['status'],
list: json['list'],
);
}
}
And you can use it like this
final jsonString = '{ "status": "1", "list": { "4": [ { "id": "1289", "t": "Mutton biriyani", "p": "21", "i": "1289_5305.jpg", "v": "0" }, { "id": "1288", "t": "Chicken biriyani", "p": "14", "i": "1288_5339.jpg", "v": "0" } ] } }';
final jsonMap = jsonDecode(jsonString);
final data = Model.fromJson(jsonMap);
Note that the List class is a basic type in dart, so it is not suitable for your json structure. In this case, you need to define a custom class for the "list" field.
class FoodList {
String status;
Map<String, List<Food>> list;
FoodList({this.status, this.list});
factory FoodList.fromJson(Map<String, dynamic> json) {
var list = json['list'] as Map;
var foodList = list.map((key, value) {
return MapEntry(key, (value as List).map((e) => Food.fromJson(e)).toList());
});
return FoodList(status: json['status'], list: foodList);
}
}
class Food {
String id;
String title;
String price;
String image;
String v;
Food({this.id, this.title, this.price, this.image, this.v});
factory Food.fromJson(Map<String, dynamic> json) {
return Food(
id: json['id'],
title: json['t'],
price: json['p'],
image: json['i'],
v: json['v']);
}
}
Related
I've been trying to get a column from a array into a list, I'm can't seem to figure how to do it, and I couldn't find a solution online. Most of the array i find only aren't nested.
{
"status": true,
"data": {
"1": [
{
"id": "1",
"name": "500MB [SME]",
"price": "220",
"telco_price": "0"
},
{
"id": "2",
"name": "1GB [SME]",
"price": "410",
"telco_price": "0"
},
{
"id": "3",
"name": "2GB [SME]",
"price": "800",
"telco_price": "0"
},
],
"2": [
{
"id": "AIR1000",
"name": "1.5GB ",
"price": "920",
"telco_price": "920"
},
{
"id": "AIR2000",
"name": "4.5GB",
"price": "1840",
"telco_price": "1840"
},
{
"id": "AIR2500",
"name": "6GB",
"price": "2300",
"telco_price": "2300"
}
],
"3": [
{
"id": "9MOB500",
"name": "500MB",
"price": "400",
"telco_price": "400"
},
{
"id": "9MOB1000",
"name": "1.5GB",
"price": "850",
"telco_price": "850"
},
{
"id": "9MOB2000",
"name": "2GB",
"price": "1020",
"telco_price": "1020"
},
]
}
}
firstly, i want to get all names into a list variable which i can then populate easily on one of my page...
i want it into var nameList = []; where its' stated "1" then the next into another variable like that
Do on fetch like
import 'package:http/http.dart' as http;
....
List<DataClass> nameList = [];
fetch() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
MyResponse myResponse = MyResponse.fromJson(data);
final values = myResponse.data?.values;
if (values != null) {
for (final v in values) {
if(v!=null) nameList.addAll(v.toList());
}
}
}
}
Try this model class
import 'dart:convert';
class MyResponse {
final bool? status;
final Map<String, List<DataClass>?>? data;
MyResponse({
this.status,
required this.data,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(status != null){
result.addAll({'status': status});
}
if(data != null){
result.addAll({'data': data});
}
return result;
}
factory MyResponse.fromMap(Map<String, dynamic> map) {
return MyResponse(
status: map['status'],
data: Map<String, List<DataClass>?>.from(map['data']),
);
}
String toJson() => json.encode(toMap());
factory MyResponse.fromJson(String source) => MyResponse.fromMap(json.decode(source));
}
class DataClass {
final String? id;
final String? name;
final String? price;
final String? telco_price;
DataClass({
this.id,
this.name,
this.price,
this.telco_price,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (id != null) {
result.addAll({'id': id});
}
if (name != null) {
result.addAll({'name': name});
}
if (price != null) {
result.addAll({'price': price});
}
if (telco_price != null) {
result.addAll({'telco_price': telco_price});
}
return result;
}
factory DataClass.fromMap(Map<String, dynamic> map) {
return DataClass(
id: map['id'],
name: map['name'],
price: map['price'],
telco_price: map['telco_price'],
);
}
String toJson() => json.encode(toMap());
factory DataClass.fromJson(String source) =>
DataClass.fromMap(json.decode(source));
}
I'm trying to parse a json file using a custom model, I always get the error type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>' and I don't know how I can fix my code. Also is it a good idea to always use nullable type in variables when you parse json files?
This is a Json example of my data:
{
"businesses": [{
"id": "1",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
},
{
"id": "2",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
}
]
}
Here is the model code I've made in order to parse the Json:
class BusinessSearch {
final List<BusinessTest> businesses;
final int total;
BusinessSearch(this.businesses, this.total);
BusinessSearch.fromJson(Map<String, dynamic> json)
: businesses = json['businesses'],
total = json['total'];
}
class BusinessTest {
final String? name;
final String? imageUrl;
final bool? isClosed;
final String? url;
final int? reviewCount;
BusinessTest(
this.name, this.imageUrl, this.isClosed, this.url, this.reviewCount);
BusinessTest.fromJson(Map<String, dynamic> json)
: name = json['name'],
imageUrl = json['image_url'],
isClosed = json['is_closed'],
url = json['url'],
reviewCount = json['review_count'];
}
This is how I'm trying to parse it:
void getData() async {
try {
String url = 'url';
NetworkHelp network = NetworkHelp(url: url);
var data = await network.getData();
Map<String, dynamic> businessMap = await jsonDecode(data);
var business = BusinessSearch.fromJson(businessMap);
} catch (e) {
print(e);
}
}
You have to update your BusinessSearch model like this.
class BusinessSearch {
BusinessSearch({
this.businesses,
this.total,
});
List<Business> businesses = [];
int total;
factory BusinessSearch.fromJson(Map<String, dynamic> json) => BusinessSearch(
businesses: List<Business>.from(json["businesses"].map((x) => Business.fromJson(x))),
total: json['total']
);
Map<String, dynamic> toJson() => {
"businesses": List<dynamic>.from(businesses.map((x) => x.toJson())),
"total": total,
};
}
class Business {
Business({
this.id,
this.alias,
this.name,
this.imageUrl,
this.isClosed,
this.url,
this.reviewCount,
this.rating,
});
String id;
String alias;
String name;
String imageUrl;
bool isClosed;
String url;
int reviewCount;
int rating;
factory Business.fromJson(Map<String, dynamic> json) => Business(
id: json["id"],
alias: json["alias"],
name: json["name"],
imageUrl: json["image_url"],
isClosed: json["is_closed"],
url: json["url"],
reviewCount: json["review_count"],
rating: json["rating"],
);
Map<String, dynamic> toJson() => {
"id": id,
"alias": alias,
"name": name,
"image_url": imageUrl,
"is_closed": isClosed,
"url": url,
"review_count": reviewCount,
"rating": rating,
};
}
hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend
"meta": {
"code": 200,
"status": "success",
"message": "Data list transaksi berhasil diambil"
},
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1,
}
}
]
}
],
}
}
response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'
for better understanding my question ill provide full model, provider and my services
this is my service getOrderList() function that i call in the futureBuilder
var url = '$baseUrl/transaction';
var headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ${userModel.token}'
};
var response = await http.get(Uri.parse(url), headers: headers);
// print(response.body);
// print('berhasil get kategori');
if (response.statusCode == 200) {
List data = json.decode(response.body)['data']['data'];
List<TransactionModel> transaction = [];
for (var item in data) {
transaction.add(TransactionModel.fromJson(item));
}
// print(transaction);
return transaction;
} else {
throw Exception('Gagal get Categori');
}
}
and this is my model code
class TransactionModel {
int id;
int users_id;
String invoice;
int seat_number;
double total_price;
String payment_method;
String status;
List items;
// List menu;
TransactionModel({
this.id,
this.users_id,
this.invoice,
this.seat_number,
this.total_price,
this.payment_method,
this.status,
this.items,
// this.menu,
});
TransactionModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
users_id = json['users_id'];
invoice = json['invoice'];
seat_number = json['seat_number'];
total_price = double.parse(json['total_price'].toString());
payment_method = json['payment_method'];
status = json['status'];
items = json['items'];
// menu = json['items']['menus'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'users_id': users_id,
'invoice': invoice,
'seat_number': seat_number,
'items': items,
'total_price': total_price,
'payment_method': payment_method,
'status': status,
// 'menu': menu,
};
}
}
i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?
It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.
Json
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1
}
}
]
}
Model class
// To parse this JSON data, do
//
// final transactionModel = transactionModelFromMap(jsonString);
import 'dart:convert';
class TransactionModel {
TransactionModel({
this.id,
this.usersId,
this.invoice,
this.seatNumber,
this.totalPrice,
this.paymentMethod,
this.status,
this.items,
});
final int id;
final int usersId;
final String invoice;
final int seatNumber;
final int totalPrice;
final String paymentMethod;
final String status;
final List<Item> items;
factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
id: json["id"],
usersId: json["users_id"],
invoice: json["invoice"],
seatNumber: json["seat_number"],
totalPrice: json["total_price"],
paymentMethod: json["payment_method"],
status: json["status"],
items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"id": id,
"users_id": usersId,
"invoice": invoice,
"seat_number": seatNumber,
"total_price": totalPrice,
"payment_method": paymentMethod,
"status": status,
"items": List<dynamic>.from(items.map((x) => x.toMap())),
};
}
class Item {
Item({
this.id,
this.menusId,
this.transactionsId,
this.quantity,
this.menus,
});
final int id;
final int menusId;
final int transactionsId;
final int quantity;
final Menus menus;
factory Item.fromJson(String str) => Item.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Item.fromMap(Map<String, dynamic> json) => Item(
id: json["id"],
menusId: json["menus_id"],
transactionsId: json["transactions_id"],
quantity: json["quantity"],
menus: Menus.fromMap(json["menus"]),
);
Map<String, dynamic> toMap() => {
"id": id,
"menus_id": menusId,
"transactions_id": transactionsId,
"quantity": quantity,
"menus": menus.toMap(),
};
}
class Menus {
Menus({
this.id,
this.name,
this.price,
this.description,
this.categoriesId,
});
final int id;
final String name;
final int price;
final String description;
final int categoriesId;
factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Menus.fromMap(Map<String, dynamic> json) => Menus(
id: json["id"],
name: json["name"],
price: json["price"],
description: json["description"],
categoriesId: json["categories_id"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"description": description,
"categories_id": categoriesId,
};
}
I will really be happy for my question to be answered. i don't really know how to display all fetched data in a widget in flutter, i am only getting a single data.
This is how my Api response looks like
{
"cartItems": [
{
"product": {
"_id": "61b0a14b4ce2a01b914ab953",
"name": "Total1",
"size": "1kg",
"price": 700,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 2,
"price": 1400,
"type": "Refil",
"_id": "61c99030eebcb51e0f2a9a37"
},
{
"product": {
"_id": "61b0a18c4ce2a01b914ab959",
"name": "Total3",
"size": "3kg",
"price": 1800,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 1,
"price": 1800,
"type": "Refil",
"_id": "61c9903feebcb51e0f2a9a3d"
},
{
"product": {
"_id": "61aa6cb89b2046e5116fabc4",
"name": "NNPC",
"size": "15kg",
"price": 17000,
"isLPG": true
},
"vendor": "61bde0f39dfb5060de241d24",
"vendorName": "NNPC NG",
"vendorLogo": "/public/o7452L7tJ-nnpc-logo.png",
"quantity": 3,
"price": 51000,
"type": "Refil",
"_id": "61c99067eebcb51e0f2a9a51"
}
]
}
This is the generated model
class GetCartItems {
List<CartItems>? cartItems;
GetCartItems({this.cartItems});
GetCartItems.fromJson(Map<String, dynamic> json) {
if (json['cartItems'] != null) {
cartItems = <CartItems>[];
json['cartItems'].forEach((v) {
cartItems!.add(new CartItems.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cartItems != null) {
data['cartItems'] = this.cartItems!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItems {
Product? product;
String? vendor;
String? vendorName;
String? vendorLogo;
int? quantity;
int? price;
String? type;
String? sId;
CartItems(
{this.product,
this.vendor,
this.vendorName,
this.vendorLogo,
this.quantity,
this.price,
this.type,
this.sId});
CartItems.fromJson(Map<String, dynamic> json) {
product =
json['product'] != null ? new Product.fromJson(json['product']) : null;
vendor = json['vendor'];
vendorName = json['vendorName'];
vendorLogo = json['vendorLogo'];
quantity = json['quantity'];
price = json['price'];
type = json['type'];
sId = json['_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.product != null) {
data['product'] = this.product!.toJson();
}
data['vendor'] = this.vendor;
data['vendorName'] = this.vendorName;
data['vendorLogo'] = this.vendorLogo;
data['quantity'] = this.quantity;
data['price'] = this.price;
data['type'] = this.type;
data['_id'] = this.sId;
return data;
}
}
class Product {
String? sId;
String? name;
String? size;
int? price;
bool? isLPG;
Product({this.sId, this.name, this.size, this.price, this.isLPG});
Product.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
size = json['size'];
price = json['price'];
isLPG = json['isLPG'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['name'] = this.name;
data['size'] = this.size;
data['price'] = this.price;
data['isLPG'] = this.isLPG;
return data;
}
}
This is my controller class
class GCP extends GetxController {
var log = Logger();
FlutterSecureStorage storage = FlutterSecureStorage();
var getCartItems = GetCartItems();
#override
void onInit() {
// TODO: implement onInit
super.onInit();
getCartItems2();
}
void getCartItems2() async {
try {
String? token = await storage.read(key: "token");
String postURL = NetworkHandler().baseurl + ApiUtil.getCartItems;
Map<String, String> headers = {
"Authorization": "Bearer $token",
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8'
};
var response = await http.get(Uri.parse(postURL), headers: headers);
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
getCartItems = GetCartItems.fromJson(body);
update();
} else {
print('Something went wrong');
}
} catch (ex) {
print({ex, 'An error occured, cannot get cart items'});
}
}
}
This is my view, where i am displaying just a single data
import 'package:flutter/material.dart';
import 'package:gasapp_customer/src/controllers/GetCartPostController.dart';
import 'package:get/get.dart';
class GetCart extends StatelessWidget {
final gcp = Get.put(GCP());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child:
Text(gcp.getCartItems.cartItems![0].product!.name.toString()),
),
],
),
),
);
}
}
So my question is how can i display all the data from my response?
You can use ListView or GridView. If the widget that you will show will be same for all instances except the data provided to it, use GridView.builder.
for more info on ListView and GridView, go to:
https://api.flutter.dev/flutter/widgets/GridView-class.html
https://api.flutter.dev/flutter/widgets/ListView-class.html
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.