skip to Main Content

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


  1. You just need to change

    print(testModel);
    

    to this:

    print(jsonEncode(testModel));
    

    jsonEncode() will call the method toJson() on your testModel, transforming it into a map. Further informations here: https://api.flutter.dev/flutter/dart-convert/jsonEncode.html

    Login or Signup to reply.
  2. Maybe you should make sure an Address existe before setting the city:

    testModel.name = 'something';
    testModel.address ??= Address();
    testModel.address!.city = 'London';
    

    If testModel.address is not set, testModel.address?.city = 'London'; will have no effect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search