Converting a map into list of objects in flutter - 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).

Related

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

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

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

I'm trying to parse a json file using a custom model, I always get the error type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>' and I don't know how I can fix my code. Also is it a good idea to always use nullable type in variables when you parse json files?
This is a Json example of my data:
{
"businesses": [{
"id": "1",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
},
{
"id": "2",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
}
]
}
Here is the model code I've made in order to parse the Json:
class BusinessSearch {
final List<BusinessTest> businesses;
final int total;
BusinessSearch(this.businesses, this.total);
BusinessSearch.fromJson(Map<String, dynamic> json)
: businesses = json['businesses'],
total = json['total'];
}
class BusinessTest {
final String? name;
final String? imageUrl;
final bool? isClosed;
final String? url;
final int? reviewCount;
BusinessTest(
this.name, this.imageUrl, this.isClosed, this.url, this.reviewCount);
BusinessTest.fromJson(Map<String, dynamic> json)
: name = json['name'],
imageUrl = json['image_url'],
isClosed = json['is_closed'],
url = json['url'],
reviewCount = json['review_count'];
}
This is how I'm trying to parse it:
void getData() async {
try {
String url = 'url';
NetworkHelp network = NetworkHelp(url: url);
var data = await network.getData();
Map<String, dynamic> businessMap = await jsonDecode(data);
var business = BusinessSearch.fromJson(businessMap);
} catch (e) {
print(e);
}
}
You have to update your BusinessSearch model like this.
class BusinessSearch {
BusinessSearch({
this.businesses,
this.total,
});
List<Business> businesses = [];
int total;
factory BusinessSearch.fromJson(Map<String, dynamic> json) => BusinessSearch(
businesses: List<Business>.from(json["businesses"].map((x) => Business.fromJson(x))),
total: json['total']
);
Map<String, dynamic> toJson() => {
"businesses": List<dynamic>.from(businesses.map((x) => x.toJson())),
"total": total,
};
}
class Business {
Business({
this.id,
this.alias,
this.name,
this.imageUrl,
this.isClosed,
this.url,
this.reviewCount,
this.rating,
});
String id;
String alias;
String name;
String imageUrl;
bool isClosed;
String url;
int reviewCount;
int rating;
factory Business.fromJson(Map<String, dynamic> json) => Business(
id: json["id"],
alias: json["alias"],
name: json["name"],
imageUrl: json["image_url"],
isClosed: json["is_closed"],
url: json["url"],
reviewCount: json["review_count"],
rating: json["rating"],
);
Map<String, dynamic> toJson() => {
"id": id,
"alias": alias,
"name": name,
"image_url": imageUrl,
"is_closed": isClosed,
"url": url,
"review_count": reviewCount,
"rating": rating,
};
}

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