I have a class of prices in a store. It does not accept price_range
as an input but I want it to produce a list of all the prices of the products for itself.
{
"mall":
[
{
"store_id": 1,
"price_range": [],
"products":
[
{
"product_id": 1,
"price": 9.99
}
]
},
{
"store_id": 2,
"price_range": [],
"products":
[
{
"product_id": 1,
"price": 45.99
},
{
"product_id": 2,
"price": 25.99
}
]
}
]
}
Is it possible for price_range to have the prices of the products?
For in this case:
store1 can have price_range = [9.99]
and
store2 can have price_range = [45.99, 25.99]
?
I have appended my model at the bottom. I tried to use this._price_range = product_model.map((element) => double.parse(element.price));
. Not sure yet if it is able to create the list of prices. I have removed the ProductModel class to make it shorter.
class Mall {
late List<mallModel> _mall;
List<mallModel> get mall => _mall;
Mall({required mall}){
this._mall = mall;
}
Mall.fromJson(Map<String, dynamic> json) {
if (json['contents'] != null) {
_mall = <MallModel>[];
json['mall'].forEach((v) {
_mall!.add(MallModel.fromJson(v));
});
}
}
}
class StoreModel {
int? store_id;
late List<ProductModel> _product_model;
List<ProductModel> get product_model =>_product_model;
late List<double> _price_range;
List<double> get price_range => _price_range;
StoreModel(
{required store_id;
required product_model}){
this._product_model = product_model;
this._price_range = product_model.map((element) => double.parse(element.price));
}
StoreModel.fromJson(Map<String, dynamic> json) {
store_id= json['store_id'];
if (json['products'] != null) {
_product_model = <ProductModel>[];
json['products'].forEach((v) {
_product_model.add(Product.fromJson(v));
});
}
_price_range = [];
}
}
When I try to run my app, I am getting this error
LateInitializationError: Field '_price_range@22053741' has not been initialized.
>Solution :
You should initiate _price_range
in StoreModel.fromJson
class StoreModel {
int? store_id;
late List<ProductModel> _product_model;
List<ProductModel> get product_model =>_product_model;
late List<double> _price_range;
List<double> get price_range => _price_range;
StoreModel(
{required this.store_id,
required product_model}){
this._product_model = product_model;
this._price_range = product_model.map((element) => double.parse(element.price)).toList();
}
StoreModel.fromJson(Map<String, dynamic> json) {
store_id= json['store_id'];
_product_model = <ProductModel>[];
if (json['products'] != null) {
json['products'].forEach((v) {
_product_model.add(Product.fromJson(v));
});
}
this._price_range = product_model.map((element) => double.parse(element.price)).toList();
}
}
I hope this helps!.