Error while Calculating and displaying total of Map Item in Flutter - 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;
}

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

Adding Map elements into List in Dart

I have a JSON response that is of type Map<String, dynamic> out of which I would like to extract elements into a List. I would like to know how this can be done. I have written a piece of code for that which doesn't really work and throws the error you will see below. I'm welcome to suggestions of all kinds. Below are the code, error and the JSON response:
JSON Response(I'm only interested in getting the values of the key(list) named data)
{
"status": "200",
"data": {
"current_page": 1,
"data": [ //I need the values in this list
{
"restaurant_id": 1,
"restaurant_name": "City Club",
"restaurant_address": "Street Number 17, GN Block, Sector V, Bidhannagar, Kolkata, West Bengal 700091",
"restaurant_image": "/public/assets/restaurant/6x4aJL03-36-30.jpg",
"restaurant_rating": "4",
"restaurant_rating_count": "8",
"distance": 0
},
{
"restaurant_id": 6,
"restaurant_name": "Mocambo",
"restaurant_address": "Ground Floor, 25B, Mirza Ghalib St, Taltala, Kolkata, West Bengal 700016",
"restaurant_image": "/public/assets/restaurant/A6lAQu03-41-17.jpg",
"restaurant_rating": null,
"restaurant_rating_count": null,
"distance": 14.8039003284490693346242551342584192752838134765625
},
{
"restaurant_id": 7,
"restaurant_name": "Peter Cat",
"restaurant_address": "Park St, opposite KFC Restaurant, Park Street area, Kolkata, West Bengal 700016",
"restaurant_image": "/public/assets/restaurant/RfjxvK03-44-59.jpg",
"restaurant_rating": null,
"restaurant_rating_count": null,
"distance": 47.4211446933120015501117450185120105743408203125
},
{
"restaurant_id": 8,
"restaurant_name": "Flurrys",
"restaurant_address": "Grand Trunk Rd, Barabazar, Sukhsanatantala, Chandannagar, West Bengal 712136",
"restaurant_image": "/public/assets/restaurant/Pitmxq03-47-20.jpg",
"restaurant_rating": null,
"restaurant_rating_count": null,
"distance": 116.161207301201244490584940649569034576416015625
},
{
"restaurant_id": 9,
"restaurant_name": "Karims",
"restaurant_address": "GP Block, Sector V, Bidhannagar, Kolkata, West Bengal 700091",
"restaurant_image": "/public/assets/restaurant/brmWnW03-51-13.jpg",
"restaurant_rating": null,
"restaurant_rating_count": null,
"distance": 179.675331121963466785018681548535823822021484375
}
],
"first_page_url": "https://achievexsolutions.in/current_work/eatiano/api/all_restaurant?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "https://achievexsolutions.in/current_work/eatiano/api/all_restaurant?page=1",
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "https://achievexsolutions.in/current_work/eatiano/api/all_restaurant?page=1",
"label": "1",
"active": true
},
{
"url": null,
"label": "Next »",
"active": false
}
],
"next_page_url": null,
"path": "https://achievexsolutions.in/current_work/eatiano/api/all_restaurant",
"per_page": 25,
"prev_page_url": null,
"to": 5,
"total": 5
}
}
The code that I've written:
class PopularRestaurantProvider with ChangeNotifier {
String baseUrl = 'baseUrl';
Map<String, dynamic> _restaurants = {};
List<dynamic> _restaurantList = [];
final queryParams = {'lat': '22.5735314', 'lng': '88.4331189'};
Map<String, dynamic> get restaurants {
return {..._restaurants};
}
List<dynamic> get restaurantList {
return [..._restaurantList];
}
Future<void> fetchRestaurants() async {
final url = Uri.parse(baseUrl +
'api/all_restaurant' +
'?' +
'lat=${queryParams['lat']}' +
'&' +
'lng=${queryParams['lng']}');
final response = await http.get(url);
PopularRestaurants popularRestaurants =
popularRestaurantsFromJson(response.body);
_restaurants = popularRestaurants.toJson();
_restaurants['data']['data'].forEach((key, value) => _restaurantList.add(value)); //This is where I've tried adding the elements
print('Restaurants List $_restaurantList'); //Currently this doesn't print anything
}
}
The model class that I have generated out of the response:
PopularRestaurants popularRestaurantsFromJson(String str) =>
PopularRestaurants.fromJson(json.decode(str));
String popularRestaurantsToJson(PopularRestaurants data) =>
json.encode(data.toJson());
class PopularRestaurants {
PopularRestaurants({
required this.status,
required this.data,
});
String status;
Data data;
factory PopularRestaurants.fromJson(Map<String, dynamic> json) =>
PopularRestaurants(
status: json["status"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": data.toJson(),
};
}
class Data {
Data({
required this.currentPage,
required this.data,
required this.firstPageUrl,
required this.from,
required this.lastPage,
required this.lastPageUrl,
required this.links,
required this.nextPageUrl,
required this.path,
required this.perPage,
required this.prevPageUrl,
required this.to,
required this.total,
});
int currentPage;
List<Datum> data;
String firstPageUrl;
int from;
int lastPage;
String lastPageUrl;
List<Link> links;
dynamic nextPageUrl;
String path;
int perPage;
dynamic prevPageUrl;
int to;
int total;
factory Data.fromJson(Map<String, dynamic> json) => Data(
currentPage: json["current_page"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
firstPageUrl: json["first_page_url"],
from: json["from"],
lastPage: json["last_page"],
lastPageUrl: json["last_page_url"],
links: List<Link>.from(json["links"].map((x) => Link.fromJson(x))),
nextPageUrl: json["next_page_url"],
path: json["path"],
perPage: json["per_page"],
prevPageUrl: json["prev_page_url"],
to: json["to"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"current_page": currentPage,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"first_page_url": firstPageUrl,
"from": from,
"last_page": lastPage,
"last_page_url": lastPageUrl,
"links": List<dynamic>.from(links.map((x) => x.toJson())),
"next_page_url": nextPageUrl,
"path": path,
"per_page": perPage,
"prev_page_url": prevPageUrl,
"to": to,
"total": total,
};
}
class Datum {
Datum({
required this.restaurantId,
required this.restaurantName,
required this.restaurantAddress,
required this.restaurantImage,
required this.restaurantRating,
required this.restaurantRatingCount,
required this.distance,
});
int restaurantId;
String restaurantName;
String restaurantAddress;
String restaurantImage;
dynamic restaurantRating;
dynamic restaurantRatingCount;
double distance;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
restaurantId: json["restaurant_id"],
restaurantName: json["restaurant_name"],
restaurantAddress: json["restaurant_address"],
restaurantImage: json["restaurant_image"],
restaurantRating: json["restaurant_rating"],
restaurantRatingCount: json["restaurant_rating_count"],
distance: json["distance"].toDouble(),
);
Map<String, dynamic> toJson() => {
"restaurant_id": restaurantId,
"restaurant_name": restaurantName,
"restaurant_address": restaurantAddress,
"restaurant_image": restaurantImage,
"restaurant_rating": restaurantRating,
"restaurant_rating_count": restaurantRatingCount,
"distance": distance,
};
}
class Link {
Link({
required this.url,
required this.label,
required this.active,
});
String url;
String label;
bool active;
factory Link.fromJson(Map<String, dynamic> json) => Link(
url: json["url"] == null ? null : json["url"],
label: json["label"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"url": url == null ? null : url,
"label": label,
"active": active,
};
}
The error I get at the moment:
Unhandled Exception: type '(dynamic) => dynamic' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform
#Belinda is correct in that _restaurants['data']['data'] is a List.
This is why your line here returns an error because the List itself doesn't have any keys or values.
_restaurants['data']['data'].forEach((key, value) => _restaurantList.add(value)); //This is where I've tried adding the elements
However, that solution will populate one big list with a mix of all the individual keys of each Map with no separation. Maybe that is in fact what you want, but my understanding from your question is that you wanted a list of the maps inside of _restaurants['data']['data'].
If that is the case you can simply do this instead of the line quoted above.
_restaurantList = _restaurants['data']['data'] as List;
Which will print this and you can access each index in the List as an individual Map.
Restaurants List [{restaurant_id: 1, restaurant_name: City Club, restaurant_address: Street Number 17, GN Block, Sector V, Bidhannagar, Kolkata, West Bengal 700091, restaurant_image: /public/assets/restaurant/6x4aJL03-36-30.jpg, restaurant_rating: 4, restaurant_rating_count: 8, distance: 0.0}, {restaurant_id: 6, restaurant_name: Mocambo, restaurant_address: Ground Floor, 25B, Mirza Ghalib St, Taltala, Kolkata, West Bengal 700016, restaurant_image: /public/assets/restaurant/A6lAQu03-41-17.jpg, restaurant_rating: null, restaurant_rating_count: null, distance: 14.80390032844907}, {restaurant_id: 7, restaurant_name: Peter Cat, restaurant_address: Park St, opposite KFC Restaurant, Park Street area, Kolkata, West Bengal 700016, restaurant_image: /public/assets/restaurant/RfjxvK03-44-59.jpg, restaurant_rating: null, restaurant_rating_count: null, distance: 47.421144693312}, {restaurant_id: 8, restaurant_name: Flurrys, restaurant_address: Grand Trunk Rd, Barabazar, Sukhsanatantala, Chandannaga<…>
_restaurants['data']['data'] is a List of Map so the code should be like this:
for(var item in _restaurants['data']['data']) {
item.forEach((key, value) => _restaurantList.add(value));
}

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

How to fetch json data and separate it based on a Parameter?

I have a json object here -
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "cciigcigc",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
I want to fetch it based on the ["data"]["status"] parameter; if the status is false, return a seperate list and if the status is true, return another list. I have tried to modify my current fetch method this way -
Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false
List<Post> statusComplete;
List<Post> statusInComplete;
String link = baseURL + fetchTodoByDate;
// print("printing from get task = $setter");
Stopwatch stopwatchbefore = new Stopwatch()..start();
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});
print('fetch executed in ${stopwatchbefore.elapsed}');
if (res.statusCode == 200) {
Stopwatch stopwatchafter = new Stopwatch()
..start();
var data = json.decode(res.body);
var rest = data["data"] as List;
if(identifier == true){
statusComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusComplete;
}else if(identifier == false){
statusInComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusInComplete;
}
print('statuscode executed in ${stopwatchafter.elapsed}');
Future.delayed(Duration(seconds: 5));
}
// print("List Size: ${list.length}");
}
This is the first time I am trying to fetch and separate the data this way. I have tried to look at some tutorials but none seemed to be satisfying my case.
Could i get some suggestion on how to fetch the data and then separate it based on a parameter?
check out the example below which will give the basic idea how the flow works.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final yourData = dataFromJson(jsonString);
dataList = yourData.data;
var statusComplete = dataList.where((i) => i.status == true).toList();
for (int i = 0; i < statusComplete.length; i++) {
print('This is the list for true status :${statusComplete[i].title}');
}
var statusInComplete = dataList.where((i) => i.status == false).toList();
print(statusInComplete[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(dataList[index].status.toString());
}),
)),
);
}
}
below is the model class
// 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 {
String error;
String message;
List<Datum> data;
Data({
this.error,
this.message,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
and this is the json that you specified
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "first",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "second",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "third",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
Try this model class
import 'dart:convert';
Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
class Jsonmodel {
String error;
String message;
List<Datum> data;
Jsonmodel({
this.error,
this.message,
this.data,
});
factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
use like this
var res = await http.post(Uri.encodeFull(link), headers: {"Accept":
"application/json", }, body: {"date" : setter.toString()});
Jsonmodel modeldata = jsonmodelFromJson(res);
// do your stuff
modeldata.data.foreach((data){
if(data.status){
//do your stuff
}else{
//do your stuff
}
});