Flutter : How insert dynamic list to sqflite - flutter

I have an app in flutter want to add list of data to sqlite database at initializing the database ,I have problem with the type of model.
I have this model for data :
import 'dart:convert';
List<Clubs> clubsFromMap(String str) =>
List<Clubs>.from(json.decode(str).map((x) => Clubs.fromMap(x)));
String clubsToMap(List<Clubs> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toMap())));
class Clubs {
Clubs({
this.id,
this.club,
this.leagueId,
this.price,
this.surname,
this.leagueName,
this.counter,
this.selected,
});
int id;
String club;
int leagueId;
String price;
String surname;
String leagueName;
int counter;
String selected;
factory Clubs.fromMap(Map<String, dynamic> json) => Clubs(
id: json["id"],
club: json["club"],
leagueId: json["league_id"],
price: json["price"],
surname: json["surname"],
leagueName: json["league_name"],
counter: json["counter"],
selected: json["selected"],
);
Map<String, dynamic> toMap() => {
"id": id,
"club": club,
"league_id": leagueId,
"price": price,
"surname": surname,
"league_name": leagueName,
"counter": counter,
"selected": selected,
};
}
and I have this list of data for that model :
var clubs = [
{
"id": 1,
"club": "Manchester City",
"league_id": 1,
"price": "10.00",
"surname": "MCY",
"league_name": "Premier League",
"counter": 1,
"selected": "No"
},
..................etc
]
no I want tho add this initial data to sqflite database ,I created thsi :
import 'package:sqflite/sqflite.dart';
class DataBaseService {
static final DataBaseService _instance = DataBaseService.internal();
factory DataBaseService() => _instance;
DataBaseService.internal();
Database _database;
Future<Database> get database async {
if (_database == null) {
_database = await intializeDataBase();
return _database;
}
}
Future<Database> intializeDataBase() async {
var dir = await getDatabasesPath();
var path = dir + "clubs.db";
var database =
await openDatabase(path, version: 1, onCreate: (db, version) {
db.execute('''
create table $clubsTableName(
columnId integer primary key,
$columnClub text not null,
$columnLeaueId integer,
$columnPrice double,
$columnSurname text not null,
$columnLeagueName text,
$columnCounter integer.
$columnSelected text,
)
''');
db.insert(clubsTableName,clubs.toMap());
it say that toMap() isn't defined ,if I changed it to clubsFromMap(clubs) instead of clubs.toMap() it says : The argument type 'List<Clubs>' can't be assigned to the parameter type 'Map<String, Object>'.dart(argument_type_not_assignable)
How can I solve this?

I solved it after change the list format like this:
var clubs = {"data":{
{
"id": 1,
"club": "Manchester City",
"league_id": 1,
"price": "10.00",
"surname": "MCY",
"league_name": "Premier League",
"counter": 1,
"selected": "No"
},
..................etc}
}

Related

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

Error while Calculating and displaying total of Map Item in Flutter

I have a Map which stores an API response that I intend to use throughout my Application. Although, the API part works just as I expected, the trouble begins when I try displaying the total amount of all the objects. The total amount needs to be calculated in the following way:total += product_selling_price * quantity;.
However, the logic that I have written throws the below error:
Class 'int' has no instance method '[]'.
Receiver: 0
Tried calling: []("product_selling_price")
The JSON response, the method that calculates the total and the widget from which the method is called are as follows. Also, I will mark the lines where the errors are pointed at.
The JSON response:
{
"status": "success",
"data": [
{
"cart_id": 18,
"restaurant_id": "1",
"product_id": "5",
"restaurant_name": "City Club",
"product_name": "Palak Paneer",
"product_description": "Tasty silky gravy with goodness of palak",
"product_image": "/public/assets/product/C6pGz101-42-17.jpg",
"product_selling_price": "180",
"product_status": "active",
"product_quantity": "32",
"quantity": "2"
},
{
"cart_id": 17,
"restaurant_id": "1",
"product_id": "6",
"restaurant_name": "City Club",
"product_name": "Jersey Burger",
"product_description": "Tasty yummy burgir. BURGIRRRRR",
"product_image": "/public/assets/product/1Xf0sr01-43-20.jpg",
"product_selling_price": "185",
"product_status": "active",
"product_quantity": "50",
"quantity": "2"
},
{
"cart_id": 16,
"restaurant_id": "1",
"product_id": "7",
"restaurant_name": "City Club",
"product_name": "Tibetan Soup",
"product_description": "Healthy Soup from the mountains of Tibet",
"product_image": "/public/assets/product/CgMBpm02-03-38.jpg",
"product_selling_price": "120",
"product_status": "active",
"product_quantity": "24",
"quantity": "2"
}
]
}
The class with the method:
class CartItemProvider with ChangeNotifier {
Map<String, dynamic> _cartItems = {};
List<dynamic> _individualItems = [];
Network network = Network();
String baseUrl = 'https://achievexsolutions.in/current_work/eatiano/';
double deliveryCost = 40;
double discountCost = 50;
List<dynamic> get cartItemList {
return [..._cartItemList];
}
Map<String, dynamic> get cartItems {
return {..._cartItems};
}
Future<void> fetchCartItems() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
final url = Uri.parse(baseUrl + 'api/auth/cart');
final response = await http.get(url, headers: {
'Authorization': 'Bearer ${localStorage.getString('token')}',
'Accept': 'application/json'
});
Cart cartJson = cartFromJson(response.body);
_cartItems = cartJson.toJson();
print('Cart Item $_cartItems');
}
double get itemAmount { //The method in question
double total = 0.0;
total = _cartItems['data'].fold( //The above error gets pointed from this line
0,
(price, value) =>
price +
(double.parse(price['product_selling_price']) * //To This line, at price['product_selling_price']
double.parse(price['quantity'])));
return total;
}
}
The Model Class in case someone needs to take a look:
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,
});
final String status;
final 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.quantity,
});
final int cartId;
final String restaurantId;
final String productId;
final String restaurantName;
final String productName;
final String productDescription;
final String productImage;
final String productSellingPrice;
final String productStatus;
final String productQuantity;
final 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"],
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,
"quantity": quantity,
};
}
The widget from which the itemAmount getter is called:
class CartDetailScreen extends StatefulWidget {
CartDetailScreenState createState() => CartDetailScreenState();
}
class CartDetailScreenState extends State<CartDetailScreen> {
#override
Widget build(BuildContext context) {
......
// TODO: implement build
return Scaffold(
......
body: ListView(
children: [
........
),
Text(
'₹ ${Provider.of<CartItemProvider>(context).itemAmount //This is where the itemAmount method is accessed from
}',
........
],
));
}
}
I would like to know what I need to do to fix and get rid of this error.
fold function is a reducer, first argument (you name it price) is the precedent value so it is an int not an array of int and second value (you name it value) is the current value.
So you can't use price[...] if current value is an array use value[...]
https://api.dart.dev/stable/1.10.1/dart-core/List/fold.html
Your code should be like this:
double get itemAmount {
double total = 0.0;
total = _cartItems['data'].fold(
0,
(price, value) =>
price +
(double.parse(value['product_selling_price']) *
double.parse(value['quantity'])));
return total;
}

Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic>' in type cast

I'm pretty new to Flutter and struggling to parse a JSON data of type Map which is as below. Everytime I try fetching the data and storing it, I keep getting Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic>' in type cast
{
"status": "success",
"data": [
{
"product_id": 10,
"restaurant_name": "new restaurant5",
"product_name": "Test Product new 2",
"product_desciption": "A cool new test product new 2",
"product_image": null,
"product_selling_price": "450",
"product_status": "active",
"product_quantity": "500",
"product_rating": null,
"product_rating_count": null,
"product_sell_count": null
},
{
"product_id": 9,
"restaurant_name": "new restaurant5",
"product_name": "Test Product new 1",
"product_desciption": "A cool new test product new",
"product_image": null,
"product_selling_price": "400",
"product_status": "active",
"product_quantity": "100",
"product_rating": null,
"product_rating_count": null,
"product_sell_count": null
},
{
"product_id": 8,
"restaurant_name": "new restaurant5",
"product_name": "Test Product new",
"product_desciption": "A cool new test product new",
"product_image": null,
"product_selling_price": "350",
"product_status": "active",
"product_quantity": "1000",
"product_rating": null,
"product_rating_count": null,
"product_sell_count": null
},
}
I have used used Quicktype.io to generate the Model Class from JSON to dart which is as follows:
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.status,
required this.data,
});
String status;
List<Datum> data;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
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.productId,
required this.restaurantName,
required this.productName,
required this.productDesciption,
required this.productImage,
required this.productSellingPrice,
required this.productStatus,
required this.productQuantity,
required this.productRating,
required this.productRatingCount,
required this.productSellCount,
});
int productId;
RestaurantName? restaurantName;
String productName;
String productDesciption;
String productImage;
String productSellingPrice;
ProductStatus? productStatus;
String productQuantity;
dynamic productRating;
dynamic productRatingCount;
dynamic productSellCount;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
productId: json["product_id"],
restaurantName: restaurantNameValues.map[json["restaurant_name"]],
productName: json["product_name"],
productDesciption: json["product_desciption"],
productImage:
json["product_image"] == null ? null : json["product_image"],
productSellingPrice: json["product_selling_price"],
productStatus: productStatusValues.map[json["product_status"]],
productQuantity:
json["product_quantity"] == null ? null : json["product_quantity"],
productRating: json["product_rating"],
productRatingCount: json["product_rating_count"],
productSellCount: json["product_sell_count"],
);
Map<String, dynamic> toJson() => {
"product_id": productId,
"restaurant_name": restaurantNameValues.reverse![restaurantName],
"product_name": productName,
"product_desciption": productDesciption,
"product_image": productImage == null ? null : productImage,
"product_selling_price": productSellingPrice,
"product_status": productStatusValues.reverse![productStatus],
"product_quantity": productQuantity == null ? null : productQuantity,
"product_rating": productRating,
"product_rating_count": productRatingCount,
"product_sell_count": productSellCount,
};
}
enum ProductStatus { ACTIVE }
final productStatusValues = EnumValues({"active": ProductStatus.ACTIVE});
enum RestaurantName { NEW_RESTAURANT5, RESTAURANR_2 }
final restaurantNameValues = EnumValues({
"new restaurant5": RestaurantName.NEW_RESTAURANT5,
"Restauranr 2": RestaurantName.RESTAURANR_2
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
This is the class from which I'm making the API Call:
import 'package:http/http.dart' as http;
import './providerModel.dart';
class ApiProvider with ChangeNotifier {
Map<String, dynamic> _result = {};
Future<void> fetchProduct() async {
final url = Uri.https('achievexsolutions.in', '/etiano/api/all_products');
final response = await http.get(url);
print(response);
Welcome data = welcomeFromJson(response.body); //This is probably where the error gets thrown`enter code here`
print(data);
_result = data as Map<String, dynamic>;
print(_result);
}
}
You are currently assigning an entire model class to your _result variable. What you have to do is, convert the model to a Map object and then assign it to the _result variable like so:
Welcome data = welcomeFromJson(response.body);
print(data);
_result = data.toJson();
print(_result);

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