How can Update values in complex Model in Flutter? - 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.

Related

flutter map was called on a null value

I try to get data from api. CallListDto class is empty according to user type. So, sometime this class is empty sometimes it has data. I populate dropdown menu items with this class.
My problem is, when this class is empty i got error. How can i solve this.
My model class is below
Login loginFromJson(String str) => Login.fromJson(json.decode(str));
String loginToJson(Login data) => json.encode(data.toJson());
class Login {
Login({
required this.token,
required this.callListDto,
});
String token;
List<CallListDto> callListDto;
factory Login.fromJson(Map<String, dynamic> json) => Login(
token: json["token"],
callListDto: List<CallListDto>.from(
json["callListDto"].map((x) => CallListDto.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"token": token,
"callListDto": List<dynamic>.from(callListDto.map((x) => x.toJson())),
};
}
class CallListDto {
CallListDto({
required this.callId,
required this.stationCode,
required this.callType,
});
int callId;
String stationCode;
int callType;
factory CallListDto.fromJson(Map<String, dynamic> json) => CallListDto(
callId: json["callID"],
stationCode: json["stationCode"],
callType: json["callType"],
);
Map<String, dynamic> toJson() => {
"callID": callId,
"stationCode": stationCode,
"callType": callType,
};
}
Before calling the model class check that str is not empty, for example
if (dataObject.isEmpty) return;

Saving a class within a class - Flutter

I have class "DilemmData" which I need to save:
class DilemmData {
double percent = 0;
final String title;
final String date;
List<DilemmItemData> plus = [];
List<DilemmItemData> minus = [];
DilemmData(
plus,
minus, {
this.percent = 0,
this.title = '',
this.date = '',
});
static Map<String, dynamic> toJson(DilemmData dilemm) {
return {
'percent': dilemm.percent,
'title': dilemm.title,
'date': dilemm.date,
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
'minus': dilemm.minus.map((e) => e.toJson()).toList(),
};
}
factory DilemmData.fromJson(Map<String, dynamic> json) {
return DilemmData(
json['plus'],
json['minus'],
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}
static String encode(List<DilemmData> pressure) => json.encode(
pressure
.map<Map<String, dynamic>>((dil) => DilemmData.toJson(dil))
.toList(),
);
static List<DilemmData> decode(String dilemm) =>
((json.decode(dilemm) ?? []) as List<dynamic>)
.map<DilemmData>((dil) => DilemmData.fromJson(dil))
.toList();
}
class DilemmItemData {
final int importance;
final String argument;
DilemmItemData({this.importance = 0, this.argument = ''});
Map<String, dynamic> toJson() {
return {
'importance': importance,
'argument': argument,
};
}
factory DilemmItemData.fromJson(Map<String, dynamic> json) {
return DilemmItemData(
importance: json['importance'], argument: json['argument']);
}
}
There is save function:
DilemmData dilemm = DilemmData(
percent: 0,
title: controller.text,
date: clockString);
SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
String data = jsonEncode(dilemm);
sharedPreferences.setString('dilemms', data);
But when i try to save i get this error: JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of 'DilemmData'). Does anyone know how to save?
StackOverflow says I have a lot of code, but I don't know what else to write, I'll write random letters for this: shdjfhjjsdfjhwehfwouiehuwefuwefuwheugweghuweghuiweghuwueghuweweugihwueighuwhguwhgu
Here is the function to get the data:
Future loadDillems() async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
if (sharedPreferences.containsKey('dilemms')) {
Map<String, dynamic> data =
jsonDecode(sharedPreferences.getString('dilemms')!);
MyApp.dilemmList = DilemmData.fromJson(data) as List<DilemmData>;
}
}
When converting the "top" class using its toJson() method, make sure that the subsequent classes' toJson() methods is also called. As such:
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
And you of course have to implement toJson() and fromJson() in DilemmItemData as well.
Edit:
Okey, so a couple of alternatives. First of all, you had to create the new toJson() (and soon also fromJson()) methods. That is good.
As #Ivo wrote, if you pass the object to jsonEncode as you do now, then the methods cannot be static. But you could also pass DilemmData.toJson(dilemm) as:
String data = jsonEncode(DilemmData.toJson(dilemm));
But I'd recommend as #Ivo wrote to make it non-static, as you did with the new toJson method, and of course keep the toJson in DilemmItemData, and I suggest that you write the fromJson as well...
Second edit:
Your fromJson have to be a bit sharper. Something like this:
DilemmData(
(json['plus'] as List<dynamic>)
.map((e) => DilemmItemData.fromJson(e as Map<String, dynamic>))
.toList(),
Edit 3:
You are saving one DilemmData, so you have to read it as one (1) DilemmData. Remove the as List<DilemmData>; It is not all of a sudden a List when it is one object that you save (String data = jsonEncode(dilemm);)
So do as follows:
final oneDilemmData = DilemmData.fromJson(data);
I think you need to make your toJson() non static like this:
Map<String, dynamic> toJson() {
return {
'percent': percent,
'title': title,
'date': date,
'plus': plus,
'minus': minus,
};
}
your encode could be like this then:
static String encode(List<DilemmData> pressure) => json.encode(
pressure
.map<Map<String, dynamic>>((dil) => dil.toJson())
.toList(),
);

Instance members can't be accessed from a factory constructor. Flutter Firebase

I have two problems in my code , the first one is showing on _patientFromJson
and second one is The argument type 'Object' can't be assigned to the parameter type 'Map<String, dynamic>' that showing on snapshot.data()!
class Patient{
String? name ;
String? pass ;
String? image ;
String? genre ;
DateTime? birth ;
Patient(this.name, this.pass, this.genre,
this.birth,
{this.reference});
DocumentReference? reference;
factory Patient.fromSnapshot(DocumentSnapshot snapshot) {
Patient newPatient = Patient.fromJson(snapshot.data()!);
newPatient.reference = snapshot.reference;
return newPatient;
}
factory Patient.fromJson(Map<String, dynamic> json) =>
_patientFromJson(json);
Map<String, dynamic> toJson() => _patientToJson(this);
#override
String toString() => 'name $name';
Patient _patientFromJson(Map<String, dynamic> data) {
return Patient(
data['name'],
data['pass'],
data['birth'],
data['genre'],
);
}
Map<String, dynamic> _patientToJson(Patient instance) {
return {
'name' : instance.name,
'pass': instance.pass,
'birth': instance.birth,
'genre': instance.genre,
};
}
}
Convert your snapshot data to map data
Patient newPatient = Patient.fromJson(snapshot.data()! as Map<String, dynamic>');
Updated for the first one
Try removing the reference to the instance member. And you may try with
factory Patient.fromJson(Map<String, dynamic> data) =>
Patient(
data['name'],
data['pass'],
data['birth'],
data['genre'],
);
For more about instance_member_access_from_factory read this documentation

Conversion error from object to json and back in flutter

I am trying to convert a list of objects as a json string in shared preferences.
Object class
SuggestionModel suggestionModelFromJson(String str) =>
SuggestionModel.fromJson(json.decode(str));
String suggestionModelToJson(SuggestionModel data) =>
json.encode(data.toJson());
class SuggestionModel {
SuggestionModel({
this.category,
this.icon,
this.subs,
});
eCategory? category;
IconData? icon;
List<Sub>? subs;
factory SuggestionModel.fromJson(Map<String, dynamic> json) =>
SuggestionModel(
category: json["category"],
icon: json["icon"],
subs: List<Sub>.from(json["subs"].map((x) => Sub.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"icon": icon,
"subs": List<dynamic>.from(subs!.map((x) => x.toJson())),
};
}
class Sub {
Sub({
this.subCategory,
this.values,
});
String? subCategory;
List<Value>? values;
factory Sub.fromJson(Map<String, dynamic> json) => Sub(
subCategory: json["sub_category"],
values: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sub_category": subCategory,
"values": List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
class Value {
Value({
this.subName,
this.selected,
});
String? subName;
bool? selected;
factory Value.fromJson(Map<String, dynamic> json) => Value(
subName: json["sub_name"],
selected: json["selected"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"selected": selected,
};
}
When I try to do
List<SuggestionModel> list;
String encodedData = jsonEncode(list);
it gives me an error
Converting object to an encodable object failed: Instance of 'SuggestionModel'
Im not following where the exact issue comes from. tried debugging and still no luck
How can I rectify this?
Update. I've changed the enum to a String and removed the IconData field. And the above issue had resolved.
Now when I try to get the saved Json string and convert that back to list of objects. I get an error
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<SuggestionModel>'
at this line
var t = await _dataManager.getSelectedList(s);
var addedObj = json.decode(json.decode(t!));
//here...
var list = addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
Try this:
String encodedData = jsonEncode(list.map((e) => e.toJson()).toList());
So the first thing was to update the enum property of Model class to String and remove IconData.
Then for the second issue.
update the decoding function like
List<SuggestionModel> list =
addedObj.map((e) => SuggestionModel.fromJson(e)).toList();

How to use Class in variable?

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