I want to update the city value and call a post request. I can modify and update the name property but I can modify that city.
This is the JSON.
{
"name": "something",
"address": {
"city": "something"
}
}
My model
class TestModel {
String? name;
Address? address;
TestModel({this.name, this.address});
TestModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
address =
json['address'] != null ? new Address.fromJson(json['address']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
if (this.address != null) {
data['address'] = this.address!.toJson();
}
return data;
}
}
class Address {
String? city;
Address({this.city});
Address.fromJson(Map<String, dynamic> json) {
city = json['city'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['city'] = this.city;
return data;
}
}
I don’t need the API calling code. I just want to modify and print the full model values. Thank you.
Main code:
Future<void> submit() async {
testModel.name = 'something';
testModel.address?.city = 'London';
print(testModel); //Expacted output: full model data like {"name": "something","address": {"city": "London"}
}
Expected output: full model data like
{"name": "something","address": {"city": "London"}
2
Answers
You just need to change
to this:
jsonEncode()
will call the methodtoJson()
on yourtestModel
, transforming it into a map. Further informations here: https://api.flutter.dev/flutter/dart-convert/jsonEncode.htmlMaybe you should make sure an Address existe before setting the city:
If
testModel.address
is not set,testModel.address?.city = 'London';
will have no effect.