How to use Class in variable? - flutter

I want to convert fetched data as below, but I got error and emulator shutdown!
What can I do?
Map<String, dynamic> responseClassMap = {
'$ResponseCompany': ResponseCompany,//ResponseCompany is class
'$ResponseCompanyDetail': ResponseCompanyDetail, //ResponseCompanyDetail is class
};
for (var item in responseClassMap.entries) {
if (className == item.key) {
result = responseData.map((data) => item.value.fromJson(data)).toList();
}
}
Here is class ResponseCompany.dart
#JsonSerializable()
class ResponseCompany {
final num sales, ...;
...
factory ResponseCompany.fromJson(Map<String, dynamic> json) => _$ResponseCompanyFromJson(json);
...
Here is ResponseCompany.g.dart
ResponseCompany _$ResponseCompanyFromJson(Map<String, dynamic> json) {
return ResponseCompany(
);
...
}

IMHO item.value.fromJson will not work. Since fromJson is a factory constructor, and in dart's rule, one cannot call factory constructor for a type stored in a variable. (Indeed, the problem is hidden because you create a Map<string, dynamic> and dart allow everything to be called on dynamic at compile time.)
For your specific case, you can do
Map<String, dynamic> map = {
'$ResponseCompany': (d)=>ResponseCompany.fromJson(d),//ResponseCompany is class
'$ResponseCompanyDetail': (d)=>ResponseCompanyDetail.fromJson(d), //ResponseCompanyDetail is class
};
for (var item in map.entries) {
if (className == item.key) {
result = responseData.map((data) => item.value(data)).toList();
}
}

Related

Flutter error when converting a list to a json object removing some keys

I have an error when trying to convert a list of my object to json
My error:
Unhandled Exception: type 'RxList<ItemStockEntryModel>' is not a subtype of type 'Map<dynamic, dynamic>'
My model code:
class StockEntryModel {
final int? id;
final double costFreight;
final List<ItemStockEntryModel> items;
StockEntryModel({
this.id,
required this.costFreight,
required this.items,
});
factory StockEntryModel.fromJson(Map<String, dynamic> json) =>
StockEntryModel(
id: json['id'],
costFreight: json['costFreight'],
items: json['itemStockEntries'],
);
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items,
};
Map<String, dynamic> itemsToMap() => {
'data': items,
};
String itemsToJson() {
var data = {};
final test = itemsToMap()['data'];
final mappedItems = Map<String, dynamic>.from(test) // the error occurs here on test variable
..removeWhere((key, value) => value == null || key == 'product');
print(json.encode(mappedItems));
data['itemStockEntries'] = mappedItems;
return json.encode(data);
}
}
my goal is to return a json object like this
// is not complete, only example...
{
"itemStockEntries": {
"data": [{
"id": 2
}, {
"id": 3
}]
}
}
but i need remove keys if this value is null and my key product..
I saw some similar errors, but I couldn't find the one that actually causes it
sorry for my bad english =(
My solution based on Loren codes. I expect to help someone also
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items.map((e) => e.toJson()).toList(),
};
Map<String, dynamic> itemsToMap() => {
'data': items
.map(
(e) => e.toJson()
..removeWhere(
(key, value) => key == 'product' || value == null),
)
.toList(),
};
Map<String, dynamic> modelToJson() {
Map<String, dynamic> data = {};
data['itemStockEntries'] = itemsToMap();
data['costFreight'] = costFreight;
print(json.encode(data));
return data;
}
The .from method on a map needs a map to be passed into it, and you're passing in a list. So removeWhere is looking for keys and values which don't exist the way you're doing it.
So you could clear that first error getting rid of the itemsToMap function and changing the first 2 lines of your itemsToJson function to this.
var data = {'data': items}; // an actual map that you can pass in
final mappedItems = Map<String, dynamic>.from(data) // no more error here
But that's still a map with just a single key with a value of a list. So the removeWhere is not going to do anything of value here.
The List<ItemStockEntryModel> is what you need to be iterating through.
Assuming you have json serialization setup in your ItemStockEntryModel, this is closer to what you need to do. Not a complete example because I don't know what that model looks like, but it should give you the idea.
String itemsToJson() {
Map data = {};
List<String> jsonList = []; // new list of json strings to pass into data map
for (final item in items) {
if (// item meets whatever conditions you need) {
final jsonItem = json.encode(item);
jsonList.add(jsonItem);
}
}
data['itemStockEntries'] = {'data': jsonList};
return json.encode(data);
}

json = null in fromJSON method in custom JsonConverter " freezed class with multiple constructors "

I have this class
#freezed
abstract class CartEntity with _$CartEntity {
const factory CartEntity.empty(String status, String message) = _Empty;
const factory CartEntity.notEmpty(int x) = _NotEmpty;
factory CartEntity.fromJson(Map<String, dynamic> json) =>
_$CartEntityFromJson(json);
}
And this converter
class CartEntityConverter
implements JsonConverter<CartEntity, Map<String, dynamic>> {
const CartEntityConverter();
#override
CartEntity fromJson(Map<String, dynamic> json) {
//the problem here
print(json);// null
return _Empty.fromJson(json);
}
#override
Map<String, dynamic> toJson(CartEntity object) {
return object.toJson();
}
}
And this wrapper class
#freezed
abstract class CartEntityWrapper with _$CartEntityWrapper {
const factory CartEntityWrapper(#CartEntityConverter() CartEntity cartEntity) =
CartEntityWrapperData;
factory CartEntityWrapper.fromJson(Map<String, dynamic> json) =>
_$CartEntityWrapperFromJson(json);
}
And iam called
final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
print(cartEntity);
fromJson method which in CartEntityConverter is always receive null json so what's i made wrong ?
Instead of making yet another converter class that you use directly, you could just add .fromJsonA method in the main class.
It will looks like this one:
#freezed
abstract class CartEntity with _$CartEntity {
const factory CartEntity.empty(String status, String message) = _Empty;
const factory CartEntity.notEmpty(int x) = _NotEmpty;
factory CartEntity.fromJson(Map<String, dynamic> json) =>
_$CartEntityFromJson(json);
factory CartEntity.fromJsonA(Map<String, dynamic> json) {
if (/*condition for .empty constructor*/) {
return _Empty.fromJson(json);
} else if (/*condition for .notEmpty constructor*/) {
return _NotEmpty.fromJson(json);
} else {
throw Exception('Could not determine the constructor for mapping from JSON');
}
}
}
solved by using
final cartEntity = CartEntityConverter().fromJson({'x':'y'});
print(cartEntity);
instead of
final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
print(cartEntity);
documentation have a lack at this point i tried random stuffs to make it work

Flutter check if a class have a contain a key

I'm new to flutter,
My project work when I don't use my class but I want to use class so I change my project for use that and I have some problems.
In my code how to check if the parameter that I use in my function as KeyReference exist in my class ?
And how to use my parameter keyReference for search in my list of user ?
This is my class :
class User{
int type;
String name;
num index;
User({
this.type,
this.name,
this.index,
});
User.fromJson(Map<String, dynamic> map){
type = map['type'];
distance = map['name'];
hausse = map['index'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['type'] = this.type;
data['distance'] = this.name;
data['hausse'] = this.index;
}
And this is my function :
static List<User> getListItemsEquality(var value, String keyReference, List<User> items)
{
//**************** Error ****************//
if(items == null)
{
throw MyException.noData();
}
items.forEach((item) {
// =================================================================================
// I have an error on this The method 'containsKey' isn't defined for the type 'User'.
//=================================================================================
if(!item.containsKey(keyReference)){
throw MyException.parameterNotExist();
}
});
//**************** Script ****************//
// =================================================================================
// The getter 'keyReference' isn't defined for the type 'Charge'.
//=================================================================================
return items.where((c) => (c.keyReference == value)).toList();
}

How can Update values in complex Model in Flutter?

In my flutter app , I have 5 parameters for a building Like eleveator,storeroom,parking,buildAge,rentPriceThe default value of these parameters is 0 at the beginning ,I want to update every value in this ApartemanRentOptionModel class in different steps without changing other values and finally send complete values to the server.
I have a class for Rent Apartemans Options Like This :
class ApartemanRentOptionModel {
ApartemanRentOptionModel({
this.eleveator,
this.storeroom,
this.parking,
this.buildAge,
this.rentPrice
});
bool eleveator;
bool storeroom;
bool parking;
List<BuildAge> buildAge;
List<RentPrice> rentPrice;
factory ApartemanRentOptionModel.fromJson(Map<String, dynamic> json) => ApartemanRentOptionModel(
eleveator: json["eleveator"],
storeroom: json["storeroom"],
parking: json["parking"],
buildAge: List<BuildAge>.from(json["buildAge"].map((x) => BuildAge.fromJson(x))),
rentPrice: List<RentPrice>.from(json["rentPrice"].map((x) => RentPrice.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"eleveator": eleveator,
"storeroom": storeroom,
"parking": parking,
"buildAge": List<dynamic>.from(buildAge.map((x) => x.toJson())),
"rentPrice": List<dynamic>.from(rentPrice.map((x) => x.toJson())),
};
}
class BuildAge {
BuildAge({
this.buildAgeId,
this.buildAgeTitle,
this.buildAgeValue,
});
String buildAgeId;
String buildAgeTitle;
int buildAgeValue;
factory BuildAge.fromJson(Map<String, dynamic> json) => BuildAge(
buildAgeId: json["buildAgeID"],
buildAgeTitle: json["buildAgeTitle"],
buildAgeValue: json["buildAgeValue"],
);
Map<String, dynamic> toJson() => {
"buildAgeID": buildAgeId,
"buildAgeTitle": buildAgeTitle,
"buildAgeValue": buildAgeValue,
};
}
class RentPrice {
RentPrice({
this.rentPriceId,
this.rentPriceTitle,
this.rentPriceValue,
});
String rentPriceId;
String rentPriceTitle;
double rentPriceValue;
factory RentPrice.fromJson(Map<String, dynamic> json) => RentPrice(
rentPriceId: json["rentPriceID"],
rentPriceTitle: json["rentPriceTitle"],
rentPriceValue: json["rentPriceValue"].toDouble(),
);
Map<String, dynamic> toJson() => {
"rentPriceID": rentPriceId,
"rentPriceTitle": rentPriceTitle,
"rentPriceValue": rentPriceValue,
};
}
i need to change value in some data like BuildAge or RentPrice with a function like this :
ApartemanRentOptionModel _currentApartemanData;
changeCurretAparemanData(newdata) {
_currentApartemanData.toJson().update("BuildAge", (value) => newdata)
notifyListeners();
return null;
}
But it not work and nothing changes , Please help me how to update different values of a single Model class in several time . Thank you
You can use getter or setter function in model .getter function use for get value from model and setter use for set or update value in model.

How to convert an array to a dart object

I have the following structure that is returned from my API. How do I convert it to a dart object?
[
{
"stateName": "Alabama",
"stateAbbr": "AL"
},
{
"stateName": "Alaska",
"stateAbbr": "AK"
}
]
Basically, I want to display a flutter dropdown box with the stateName value..
It's a list of maps.
first make a State class:
class State{
final String stateName;
final String stateAbbr;
State({
this.stateName,
this.stateAbbr,
}) ;
factory State.fromJson(Map<String, dynamic> json){
return new State(
id: json['stateName'],
title: json['stateAbbr'],
);
}
}
then list of States:
class StatesList {
final List<State> States;
StatesList({
this.States,
});
factory StatesList.fromJson(List<dynamic> parsedJson) {
List<State> States = new List<State>();
States = parsedJson.map((i)=>State.fromJson(i)).toList();
return new StatesList(
States: States,
);
}
}
for more information read this article
class State {
String stateName;
String stateAbbr;
State({this.stateName, this.stateAbbr});
State.fromJson(Map<String, dynamic> json) {
stateName = json['stateName'];
stateAbbr = json['stateAbbr'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['stateName'] = this.stateName;
data['stateAbbr'] = this.stateAbbr;
return data;
}
}
use this website [https://javiercbk.github.io/json_to_dart/][1] it can help you to convert any object JSON to Dart class, and after that, you should use List Object of type State.