How to Parse Nested JSON ln Flutter? - flutter

{
"data": {
"Address": "ff9",
"CityID": "1",
"CityName": "Ahmedabad",
"CompanyName": "bs Soffy",
"CreditDays": "12",
"CusotmerID": "45",
"Email": "f#gmail.com",
"GSTNo": "1234",
"IsApproved": "False",
"Lat": "",
"Long": "",
"Mobile": "1234567890",
"Pincode": "",
"Route": "",
"StateID": "1",
"StateName": "Gujrat",
"UniqueNumber": ""
},
"message": "Data updated successfully",
"status": 200
}
List<GetCustomer> Customerlist = [];
Future<List<GetCustomer>> getPostApi() async {
final response = await http.post(
Uri.parse(
'XYZ'),
headers: {
"Content-Type": "application/json",
"Charset": "utf-8",
},
body: (jsonEncode({'UserID': 1})));
if (response.statusCode == 200) {
// Map<String, dynamic> map = json.decode(response.body);
Map<String, dynamic> map =
new Map<String, dynamic>.from(json.decode(response.body));
List<dynamic> data = map["data"];
Customerlist.clear();
for (var i in data) {
Customerlist.add(GetCustomer.fromJson(i));
}
return Customerlist;
} else {
return Customerlist;
}
} -> Eror When Calling

You can use app.quicktype.io or any other online sites for parsing your model so fast. Otherwise you need to write manually.
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
Data({
this.data,
this.message,
this.status,
});
DataClass data;
String message;
int status;
factory Data.fromJson(Map<String, dynamic> json) => Data(
data: DataClass.fromJson(json["data"]),
message: json["message"],
status: json["status"],
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
"message": message,
"status": status,
};
}
class DataClass {
DataClass({
this.address,
this.cityId,
this.cityName,
this.companyName,
this.creditDays,
this.cusotmerId,
this.email,
this.gstNo,
this.isApproved,
this.lat,
this.long,
this.mobile,
this.pincode,
this.route,
this.stateId,
this.stateName,
this.uniqueNumber,
});
String address;
String cityId;
String cityName;
String companyName;
String creditDays;
String cusotmerId;
String email;
String gstNo;
String isApproved;
String lat;
String long;
String mobile;
String pincode;
String route;
String stateId;
String stateName;
String uniqueNumber;
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
address: json["Address"],
cityId: json["CityID"],
cityName: json["CityName"],
companyName: json["CompanyName"],
creditDays: json["CreditDays"],
cusotmerId: json["CusotmerID"],
email: json["Email"],
gstNo: json["GSTNo"],
isApproved: json["IsApproved"],
lat: json["Lat"],
long: json["Long"],
mobile: json["Mobile"],
pincode: json["Pincode"],
route: json["Route"],
stateId: json["StateID"],
stateName: json["StateName"],
uniqueNumber: json["UniqueNumber"],
);
Map<String, dynamic> toJson() => {
"Address": address,
"CityID": cityId,
"CityName": cityName,
"CompanyName": companyName,
"CreditDays": creditDays,
"CusotmerID": cusotmerId,
"Email": email,
"GSTNo": gstNo,
"IsApproved": isApproved,
"Lat": lat,
"Long": long,
"Mobile": mobile,
"Pincode": pincode,
"Route": route,
"StateID": stateId,
"StateName": stateName,
"UniqueNumber": uniqueNumber,
};
}

Related

Dio no parsing Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

I’m trying to parse one object from a Json response. My response.data is of type ‘_InternalLinkedHashMap<String, dynamic>’. I would like to transform it to the type of my object. So for doing that I use the method fromJson of my class.
Class code:
import 'dart:convert';
import 'package:.../stl/store_stl.dart';
class StoreSTLModel extends StoreSTL {const StoreSTLModel({
required String storeId,
required String storeName,
required String subContextUrl,
required List<dynamic> openingEvent,
required List<dynamic> closingEvent,
}) : super(
storeId: storeId,
storeName: storeName,
subContextUrl: subContextUrl,
openingEvent: openingEvent,
closingEvent:closingEvent ,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'storeId': storeId,
'storeName': storeName,
'subContextUrl': subContextUrl,
'openingEvent': openingEvent.toList(),
'closingEvent': closingEvent.toList(),
};
}
factory StoreSTLModel.fromMap(Map<String, dynamic> map) {
return StoreSTLModel(
storeId: map['storeId'] as String ,
storeName: map["storeName"] as String,
subContextUrl: map["subContextUrl"] as String,
openingEvent: List<dynamic>.from(map["openingEvent"] as List<dynamic>),
closingEvent: List<dynamic>.from(map["closingEvent"] as List<dynamic>),
);
}
String toJson() => json.encode(toMap());
factory StoreSTLModel.fromJson(String source) => StoreSTLModel.fromMap(json.decode(source) as Map<String, dynamic>);
}
the code of my request is as follow: (I’m using Dio package)
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
//get store from api STL (for now store id is hardcode)
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
Response? response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
print('apiSTLData type response.data ${ apiSTLData.runtimeType}');
//prints: apiSTLData type response.data _InternalLinkedHashMap<String, dynamic>
}on Exception {
null;
print('apiSTLData Exception');
}
}
print('apiSTLData type response.data[store] ${apiSTLData['store'].runtimeType}');
//prints: apiSTLData type response.data[store] _InternalLinkedHashMap<String, dynamic>
return StoreSTLModel.fromJson(apiSTLData['store']);
}
}
when I try to run, I’m having the error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
so I don’t understand why it is not being parsed. and I don’t understand why the response is of this type ‘_InternalLinkedHashMap<String, dynamic>’ I'm a beginner in Dart. Could you please help me to understand. Thanks in advance :)
{
"store": {
"storeId": "30264",
"storeName": "xxxxx",
"subContextUrl": "hxxxu-xxxxx",
"type": "STORE",
"address": {
"label": null,
"zipcode": "xxxx",
"city": "xxxx",
"countryCode": "xxxx",
"lines": [
"xxxxxxxx",
""
]
},
"openingEvent": [],
"closingEvent": [],
"dayHours": {
"day": "THURSDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
"driveHours": {
"timezone": "xxxxxx",
"openHourList": [
{
"day": "MONDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
{
"day": "SUNDAY",
"morningOpeningHour": null,
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": null
}
]
},
"eservices": [
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 2,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 4,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 39,
"serviceName": "xxxxx"
}
],
"services": [
"xxxxxx",
"xxxxx",
"xxxxxxx"
],
"additionalStoreInfo": {
"status": "xxxxx",
"commercialSignLabel": "xxxxx"
}
}
}
This is model class
import 'dart:convert';
class StoreSTLModel {
StoreSTLModel({
required this.store,
});
final Store store;
factory StoreSTLModel.fromJson(String str) => StoreSTLModel.fromMap(json.decode(str));
factory StoreSTLModel.fromMap(Map<String, dynamic> json) => StoreSTLModel(
store: Store.fromMap(json["store"]),
);
Map<String, dynamic> toMap() => {
"store": store.toMap(),
};
}
class Store {
Store({
required this.storeId,
required this.storeName,
required this.subContextUrl,
required this.type,
required this.address,
required this.openingEvent,
required this.closingEvent,
required this.dayHours,
required this.driveHours,
required this.eservices,
required this.services,
required this.additionalStoreInfo,
});
final String storeId;
final String storeName;
final String subContextUrl;
final String type;
final Address address;
final List<dynamic> openingEvent;
final List<dynamic> closingEvent;
final DayHours dayHours;
final DriveHours driveHours;
final List<Eservice> eservices;
final List<String> services;
final AdditionalStoreInfo additionalStoreInfo;
factory Store.fromMap(Map<String, dynamic> json) => Store(
storeId: json["storeId"],
storeName: json["storeName"],
subContextUrl: json["subContextUrl"],
type: json["type"],
address: Address.fromMap(json["address"]),
openingEvent: List<dynamic>.from(json["openingEvent"].map((x) => x)),
closingEvent: List<dynamic>.from(json["closingEvent"].map((x) => x)),
dayHours: DayHours.fromMap(json["dayHours"]),
driveHours: DriveHours.fromMap(json["driveHours"]),
eservices: List<Eservice>.from(json["eservices"].map((x) => Eservice.fromMap(x))),
services: List<String>.from(json["services"].map((x) => x)),
additionalStoreInfo: AdditionalStoreInfo.fromMap(json["additionalStoreInfo"]),
);
Map<String, dynamic> toMap() => {
"storeId": storeId,
"storeName": storeName,
"subContextUrl": subContextUrl,
"type": type,
"address": address.toMap(),
"openingEvent": List<dynamic>.from(openingEvent.map((x) => x)),
"closingEvent": List<dynamic>.from(closingEvent.map((x) => x)),
"dayHours": dayHours.toMap(),
"driveHours": driveHours.toMap(),
"eservices": List<dynamic>.from(eservices.map((x) => x.toMap())),
"services": List<dynamic>.from(services.map((x) => x)),
"additionalStoreInfo": additionalStoreInfo.toMap(),
};
}
class AdditionalStoreInfo {
AdditionalStoreInfo({
required this.status,
required this.commercialSignLabel,
});
final String status;
final String commercialSignLabel;
factory AdditionalStoreInfo.fromMap(Map<String, dynamic> json) => AdditionalStoreInfo(
status: json["status"],
commercialSignLabel: json["commercialSignLabel"],
);
Map<String, dynamic> toMap() => {
"status": status,
"commercialSignLabel": commercialSignLabel,
};
}
class Address {
Address({
required this.label,
required this.zipcode,
required this.city,
required this.countryCode,
required this.lines,
});
final dynamic label;
final String zipcode;
final String city;
final String countryCode;
final List<String> lines;
factory Address.fromMap(Map<String, dynamic> json) => Address(
label: json["label"],
zipcode: json["zipcode"],
city: json["city"],
countryCode: json["countryCode"],
lines: List<String>.from(json["lines"].map((x) => x)),
);
Map<String, dynamic> toMap() => {
"label": label,
"zipcode": zipcode,
"city": city,
"countryCode": countryCode,
"lines": List<dynamic>.from(lines.map((x) => x)),
};
}
class DayHours {
DayHours({
required this.day,
required this.morningOpeningHour,
required this.morningClosingHour,
required this.afternoonOpeningHour,
required this.afternoonClosingHour,
});
final String day;
final String morningOpeningHour;
final dynamic morningClosingHour;
final dynamic afternoonOpeningHour;
final String afternoonClosingHour;
factory DayHours.fromMap(Map<String, dynamic> json) => DayHours(
day: json["day"],
morningOpeningHour: json["morningOpeningHour"],
morningClosingHour: json["morningClosingHour"],
afternoonOpeningHour: json["afternoonOpeningHour"],
afternoonClosingHour: json["afternoonClosingHour"],
);
Map<String, dynamic> toMap() => {
"day": day,
"morningOpeningHour": morningOpeningHour,
"morningClosingHour": morningClosingHour,
"afternoonOpeningHour": afternoonOpeningHour,
"afternoonClosingHour": afternoonClosingHour,
};
}
class DriveHours {
DriveHours({
required this.timezone,
required this.openHourList,
});
final String timezone;
final List<DayHours> openHourList;
factory DriveHours.fromMap(Map<String, dynamic> json) => DriveHours(
timezone: json["timezone"],
openHourList: List<DayHours>.from(json["openHourList"].map((x) => DayHours.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"timezone": timezone,
"openHourList": List<dynamic>.from(openHourList.map((x) => x.toMap())),
};
}
class Eservice {
Eservice({
required this.website,
required this.linkTitle,
required this.linklabel,
required this.serviceId,
required this.serviceName,
});
final String website;
final dynamic linkTitle;
final dynamic linklabel;
final int serviceId;
final String serviceName;
factory Eservice.fromMap(Map<String, dynamic> json) => Eservice(
website: json["website"],
linkTitle: json["linkTitle"],
linklabel: json["linklabel"],
serviceId: json["serviceId"],
serviceName: json["serviceName"],
);
Map<String, dynamic> toMap() => {
"website": website,
"linkTitle": linkTitle,
"linklabel": linklabel,
"serviceId": serviceId,
"serviceName": serviceName,
};
}
This is Dio class
import 'dart:convert';
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
final response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
if (response.statusCode == 200) {
//Try them, one of them will work.
return StoreSTLModel.fromMap(apiSTLData);
return StoreSTLModel.fromJson(apiSTLData);
} else {
throw Exception("404 error");
}
} on DioError catch (e) {
return Future.error(e.message);
}
}
}
}
Try this.

Flutter - Dart parsing json data array returns type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>'

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,
};
}

Converting a map into list of objects in flutter

I'm pretty new to Flutter and still struggling to understand a few things. My objective right now is to place map objects inside a list the logic for which that I've written hasn't been kind. I would therefore need suggestions as to how this can be achieved. The code I've written by far is below:
class CartItemProvider with ChangeNotifier {
Map<String, dynamic> _cartItems = {};
var _cartItemList = [];
List<dynamic> _individualItems = [];
Network network = Network();
String baseUrl = 'https://achievexsolutions.in/current_work/eatiano/';
double deliveryCost = 40;
double discountCost = 50;
Map<String, dynamic> get cartItems {
return {..._cartItems};
}
Future<void> fetchCartItems() async {
final url = Uri.parse(baseUrl + 'api/auth/cart');
final response = await http.get(url, headers: {
'Authorization': 'Bearer ${network.getToken()}',
'Accept': 'application/json'
});
Cart cartJson = cartFromJson(response.body);
_cartItems = cartJson.toJson();
_cartItems.forEach((key, values) => _cartItemList.add(values['data']));
print(_cartItems);
}
}
The error that I get says Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
{
"status": "success",
"data": [
{
"cart_id": 9,
"restaurant_id": "6",
"product_id": "8",
"restaurant_name": "Mocambo",
"product_name": "Kaju Paneer",
"product_description": "Tasty yummy paneer gravy dish",
"product_image": "/public/assets/product/lgml5L03-19-41.jpg",
"product_selling_price": "320",
"product_status": "active",
"product_quantity": "41",
"product_rating": null,
"product_rating_count": null,
"product_sell_count": null,
"quantity": "1"
}
]
}
I would like to store the objects in the list named data which is my main priority. The model class for the above response is below:
import 'package:meta/meta.dart';
import 'dart:convert';
Cart cartFromJson(String str) => Cart.fromJson(json.decode(str));
String cartToJson(Cart data) => json.encode(data.toJson());
class Cart {
Cart({
required this.status,
required this.data,
});
String status;
List<Datum> data;
factory Cart.fromJson(Map<String, dynamic> json) => Cart(
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 {
Datum({
required this.cartId,
required this.restaurantId,
required this.productId,
required this.restaurantName,
required this.productName,
required this.productDescription,
required this.productImage,
required this.productSellingPrice,
required this.productStatus,
required this.productQuantity,
required this.productRating,
required this.productRatingCount,
required this.productSellCount,
required this.quantity,
});
int cartId;
String restaurantId;
String productId;
String restaurantName;
String productName;
String productDescription;
String productImage;
String productSellingPrice;
String productStatus;
String productQuantity;
dynamic productRating;
dynamic productRatingCount;
dynamic productSellCount;
String quantity;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
cartId: json["cart_id"],
restaurantId: json["restaurant_id"],
productId: json["product_id"],
restaurantName: json["restaurant_name"],
productName: json["product_name"],
productDescription: json["product_description"],
productImage: json["product_image"],
productSellingPrice: json["product_selling_price"],
productStatus: json["product_status"],
productQuantity: json["product_quantity"],
productRating: json["product_rating"],
productRatingCount: json["product_rating_count"],
productSellCount: json["product_sell_count"],
quantity: json["quantity"],
);
Map<String, dynamic> toJson() => {
"cart_id": cartId,
"restaurant_id": restaurantId,
"product_id": productId,
"restaurant_name": restaurantName,
"product_name": productName,
"product_description": productDescription,
"product_image": productImage,
"product_selling_price": productSellingPrice,
"product_status": productStatus,
"product_quantity": productQuantity,
"product_rating": productRating,
"product_rating_count": productRatingCount,
"product_sell_count": productSellCount,
"quantity": quantity,
};
}
This three cases are likely the cause of your problem:
"product_rating": null,
"product_rating_count": null,
"product_sell_count": null,
because in your function below
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
you're calling .map on a null object, hence the error. You have to handle somehow the cases where json["data"] is null before calling any method on it. Is your code null-safe? That might help in cases like this because I think the IDE would warn you of such nullable cases (at least, Android Studio does).

Flutter : Get data on Nested json

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,
};
}

Flutter Calendar Map/List convert

at first I want to show you my code, which i created and then I ask my question.
This here is a basic Map which contains no information.
Map<DateTime, List<Event>> selectedEvents;
List<Event> _getEventsfromDay(DateTime date) {
return selectedEvents[date] ?? [];
}
This here is my Code:
void main() {
var jsonSource = """
{
"Events": [
{
"id": 1,
"event_name": "Cake tasting",
"event_photo": "https://dispensaries.s3.amazonaws.com/event_photo/Southern_Cali_Kush_3.jpg",
"vendor_name": {
"id": 1,
"vendor": "Tastey Cakes"
},
"refund_available": false,
"website": "www.foodcakes.com",
"share_count": 0,
"check_in_count": 0,
"street_address": "123 Fake Street",
"city": "Brooklynn",
"state": "NY",
"zipcode": "12312",
"event_tagline": "Taste my cakes",
"details": "Cake tasting",
"start_date": "2020-11-03",
"start_time": "23:33:00",
"end_time": "23:33:00",
"attendees": []
}
]
}
""";
print(convertJsonToDateMap(jsonSource));
}
Map<DateTime, List> convertJsonToDateMap(String jsonSource) {
var json = jsonDecode(jsonSource);
var jsonEvents = json['Events'];
Map<DateTime, List<String>> events = {};
for(var event in jsonEvents){
var date = parseDate(event['start_date']);
events.putIfAbsent(date, () => <String>[]);
events[date].add(event['event_name']);
}
return events;
}
DateTime parseDate(String date) {
var parts = date.split('-').map(int.tryParse).toList();
return DateTime(parts[0], parts[1], parts[2]);
}
How to write my code that the 2. code is working like the first, so that the json is stored as Map/List.
I am Flutter beginnen and dont know how to do this.
Thanks for helping!!!
Change Your Model Like This :
import 'dart:convert';
EventModel eventModelFromJson(String str) => EventModel.fromJson(json.decode(str));
String eventModelToJson(EventModel data) => json.encode(data.toJson());
class EventModel {
EventModel({
this.events,
});
List<Event> events;
factory EventModel.fromJson(Map<String, dynamic> json) => EventModel(
events: List<Event>.from(json["Events"].map((x) => Event.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Events": List<dynamic>.from(events.map((x) => x.toJson())),
};
}
class Event {
Event({
this.id,
this.eventName,
this.eventPhoto,
this.vendorName,
this.refundAvailable,
this.website,
this.shareCount,
this.checkInCount,
this.streetAddress,
this.city,
this.state,
this.zipcode,
this.eventTagline,
this.details,
this.startDate,
this.startTime,
this.endTime,
this.attendees,
});
int id;
String eventName;
String eventPhoto;
VendorName vendorName;
bool refundAvailable;
String website;
int shareCount;
int checkInCount;
String streetAddress;
String city;
String state;
String zipcode;
String eventTagline;
String details;
DateTime startDate;
String startTime;
String endTime;
List<dynamic> attendees;
factory Event.fromJson(Map<String, dynamic> json) => Event(
id: json["id"],
eventName: json["event_name"],
eventPhoto: json["event_photo"],
vendorName: VendorName.fromJson(json["vendor_name"]),
refundAvailable: json["refund_available"],
website: json["website"],
shareCount: json["share_count"],
checkInCount: json["check_in_count"],
streetAddress: json["street_address"],
city: json["city"],
state: json["state"],
zipcode: json["zipcode"],
eventTagline: json["event_tagline"],
details: json["details"],
startDate: DateTime.parse(json["start_date"]),
startTime: json["start_time"],
endTime: json["end_time"],
attendees: List<dynamic>.from(json["attendees"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"id": id,
"event_name": eventName,
"event_photo": eventPhoto,
"vendor_name": vendorName.toJson(),
"refund_available": refundAvailable,
"website": website,
"share_count": shareCount,
"check_in_count": checkInCount,
"street_address": streetAddress,
"city": city,
"state": state,
"zipcode": zipcode,
"event_tagline": eventTagline,
"details": details,
"start_date": "${startDate.year.toString().padLeft(4, '0')}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')}",
"start_time": startTime,
"end_time": endTime,
"attendees": List<dynamic>.from(attendees.map((x) => x)),
};
}
class VendorName {
VendorName({
this.id,
this.vendor,
});
int id;
String vendor;
factory VendorName.fromJson(Map<String, dynamic> json) => VendorName(
id: json["id"],
vendor: json["vendor"],
);
Map<String, dynamic> toJson() => {
"id": id,
"vendor": vendor,
};
}
To parse this JSON data, do
final eventModel = eventModelFromJson(jsonString);
Then Check the Map