Adding Map elements into List in Dart - flutter

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

Related

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).

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 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

how to get data from API, when data of API as map<dynamic , dynamic>. if data as DoctorModel inside it daysModel, inside daysModel is workTimeModel

I want to get data from API, my API data as DoctorModel inside it daysModel, inside daysModel is workTimeModel, each doctor has many days and has worktime.
I tried a lot of ways but still can't fix it.
note: I made my API from this website https://app.quicktype.io/
my code to get API data:
Response res = await get(
doctorsUrl ,
);
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
return doctors;
}
my API:
{
"id": 15,
"name": "Prof. Elton Quigley",
"about": "uHiKeKA1gq",
"stars": 5,
"location": "R59lmj1eud",
"latitude": 5,
"longitude": 5,
"notes": "yCl95VqUAz",
"days": [
{
"name": "سبت",
"pivot": {
"doctor_id": 15,
"day_id": 1,
"morning": "1",
"evening": "1"
}
},
{
"name": "أحد",
"pivot": {
"doctor_id": 15,
"day_id": 2,
"morning": "3",
"evening": "3"
}
},
{
"name": "إثنين",
"pivot": {
"doctor_id": 15,
"day_id": 3,
"morning": "5",
"evening": "5"
}
},
{
"name": "ثلاثاء",
"pivot": {
"doctor_id": 15,
"day_id": 4,
"morning": "4",
"evening": "4"
}
},
{
"name": "أربعاء",
"pivot": {
"doctor_id": 15,
"day_id": 5,
"morning": "5",
"evening": "5"
}
},
{
"name": "خميس",
"pivot": {
"doctor_id": 15,
"day_id": 6,
"morning": "4",
"evening": "4"
}
}
]
}
my DoctorModel:
// To parse this JSON data, do
//
// final doctorInfoModel = doctorInfoModelFromJson(jsonString);
import 'dart:convert';
DoctorInfoModel doctorInfoModelFromJson(String str) => DoctorInfoModel.fromJson(json.decode(str));
String doctorInfoModelToJson(DoctorInfoModel data) => json.encode(data.toJson());
class DoctorInfoModel {
DoctorInfoModel({
this.id,
this.name,
this.about,
this.stars,
this.location,
this.latitude,
this.longitude,
this.notes,
this.days,
});
int id;
String name;
String about;
int stars;
String location;
int latitude;
int longitude;
String notes;
List<Day> days;
factory DoctorInfoModel.fromJson(Map<String, dynamic> json) => DoctorInfoModel(
id: json["id"],
name: json["name"],
about: json["about"],
stars: json["stars"],
location: json["location"],
latitude: json["latitude"],
longitude: json["longitude"],
notes: json["notes"],
days: List<Day>.from(json["days"].map((x) => Day.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"about": about,
"stars": stars,
"location": location,
"latitude": latitude,
"longitude": longitude,
"notes": notes,
"days": List<dynamic>.from(days.map((x) => x.toJson())),
};
}
class Day {
Day({
this.name,
this.pivot,
});
String name;
Pivot pivot;
factory Day.fromJson(Map<String, dynamic> json) => Day(
name: json["name"],
pivot: Pivot.fromJson(json["pivot"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"pivot": pivot.toJson(),
};
}
class Pivot {
Pivot({
this.doctorId,
this.dayId,
this.morning,
this.evening,
});
int doctorId;
int dayId;
String morning;
String evening;
factory Pivot.fromJson(Map<String, dynamic> json) => Pivot(
doctorId: json["doctor_id"],
dayId: json["day_id"],
morning: json["morning"],
evening: json["evening"],
);
Map<String, dynamic> toJson() => {
"doctor_id": doctorId,
"day_id": dayId,
"morning": morning,
"evening": evening,
};
}
How can I get data correctly?
I figured out how to get data.
I replaced these two lines:
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
by these:
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
when my DoctorInfoModel is not a List, so I delete it.
Correct code to get API data:
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
print(doctorInfo.name);
print(doctorInfo.about);
print(doctorInfo.days[0].name);
print(doctorInfo.days[0].pivot.morning);
return doctorInfo;
}