0

I cannot perform a data "toJson" operation of a model and the list in it.

main model

class ExampleData {
  ExampleData({
    this.name,
    this.surname,
    this.otherList,
  });

  String name;
  String surname;
  List<ExampleOtherData> otherList;

  factory ExampleData.fromJson(Map<String, dynamic> json) =>
      ExampleData(
        name: json["name"] == null ? null : json["depoAdi"],
        surname: json["surname"] == null ? null : json["aciklama"],
        otherList: json["otherList"] == null
  ? null
      : List<ExampleOtherData>.from(
  json["otherList"].map((x) => ExampleOtherData.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
    "name": name == null ? null : name,
    "surname": surname == null ? null : surname,
    "otherList": otherList == null
        ? null
        : List<dynamic>.from(otherList.map((x) => x.toJson())),
  };
}

sub model list model linked to main model

class ExampleOtherData {
  ExampleOtherData({
    this.phone,
    this.email
  });

  String phone;
  String email;

  factory ExampleOtherData.fromJson(Map<String, dynamic> json) =>
      ExampleOtherData(
        phone: json["phone"] == null ? null : json["phone"],
        email: json["email"] == null ? null : json["email"],
      );

  Map<String, dynamic> toJson() => {
    "phone": phone == null ? null : phone,
    "email": email == null ? null : email,
  };
}

How to add main model and list model in it? How can I map the main model and the list model in it.

var newList = MainController.to.getExampleMain.map((value) => value.toJson());
await MainService.addExample(postBody: newList);

enter image description here

Thank you,

Codeguru
  • 31
  • 6

3 Answers3

1

You just need to add toList() at the end of query.

var newList = MainController.to.getExampleMain.map((value) => value.toJson()).toList();
Burak Aybi
  • 219
  • 1
  • 11
  • I tried adding it before. it gave this error. The main model is not the list, but there is the model with the list in it. Converting object to an encodable object failed: Instance of 'Future>>' – Codeguru Feb 25 '22 at 08:58
  • You are trying to use toJson method on otherList in your ExapmleData class right? And MainController.to.getExampleMain is your model to post to api. If it is right. You need to change your toJson method in ExapmleData class. Your toJson needs to be – Burak Aybi Feb 25 '22 at 09:08
  • "otherList": otherList == null ? null : otherList.map((x) => x.toJson()).toList(), – Burak Aybi Feb 25 '22 at 09:08
  • i tried but not working. controller.to.getMainExample.map((value) => value.toJson()); this not list. this is main data not list. I need to be able to add the data, which is a list, into it. can you just write this for me based on example data and otherListData. just this part. controller.to.getMainExample.map((value) => value.otherList.toJson().toList()); etc.. – Codeguru Feb 25 '22 at 09:29
  • /flutter (10334): ║ Instance of '_MapStream>' I/flutter (10334): I/flutter (10334): ╔╣ DioError ║ DioErrorType.other I/flutter (10334): ║ 'package:dio/src/dio_mixin.dart': Failed assertion: line 701 pos 16: 'data is Stream': Stream type must be `Stream`, but _MapStream> is found. – Codeguru Feb 25 '22 at 09:30
  • If it is not list change it to controller.to.getMainExample.toJson() . Because you need to map otherlist not ExampleData class – Burak Aybi Feb 25 '22 at 09:31
  • and keep "otherList": otherList == null ? null : otherList.map((x) => x.toJson()).toList() this in your toJson – Burak Aybi Feb 25 '22 at 09:32
  • i think we're close. [ERROR] Error Detail - type '(dynamic) => OtherList' is not a subtype of type '(String, dynamic) => MapEntry' of 'transform'. – Codeguru Feb 25 '22 at 10:33
  • 1
    I have successfully sent the data. thank you so much. sağol üstad kolay gelsin. – Codeguru Feb 25 '22 at 10:43
1

Basedon on model Class json string

[{name: hi, surname: joji, otherlist: [{name: kl, surname: ja}, {name: lkl, surname: lja}]}, {name: hohi, surname: jpjoji, otherlist: [{name: kl, surname: ja}, {name: lkl, surname: lja}]}]

Dartpad

Sample Code

 class MainController {
  static List<ExampleData2> to() {
    List<ExampleData2> data = [];
    List<Otherlist> otherlist = [];
    otherlist.add(new Otherlist(surname: "ja", name: "kl"));
    otherlist.add(new Otherlist(surname: "lja", name: "lkl"));
    data.add(
        new ExampleData2(name: "hi", surname: "joji", otherlist: otherlist));
    data.add(new ExampleData2(
        name: "hohi", surname: "jpjoji", otherlist: otherlist));
    return data;
  }
}
    
    
          void main() {
    
              
        //    ---------------------- json
                 var list = MainController.to().map((e) => e.toJson()).toList();
            
                print(list);
                var d = list.map((e) => ExampleData2.fromJson(e)).toList();
            
                print(d);
            }
            class ExampleData2 {
              String? name;
              String? surname;
              List<Otherlist>? otherlist;
            
              ExampleData2({this.name, this.surname, this.otherlist});
            
              ExampleData2.fromJson(Map<String, dynamic> json) {
                name = json['name'];
                surname = json['surname'];
                if (json['otherlist'] != null) {
                  otherlist = <Otherlist>[];
                  json['otherlist'].forEach((v) {
                    otherlist!.add(new Otherlist.fromJson(v));
                  });
                }
              }
            
              Map<String, dynamic> toJson() {
                final Map<String, dynamic> data = new Map<String, dynamic>();
                data['name'] = this.name;
                data['surname'] = this.surname;
                if (this.otherlist != null) {
                  data['otherlist'] = this.otherlist!.map((v) => v.toJson()).toList();
                }
                return data;
              }
            }
            
            class Otherlist {
              String? name;
              String? surname;
            
              Otherlist({this.name, this.surname});
            
              Otherlist.fromJson(Map<String, dynamic> json) {
                name = json['name'];
                surname = json['surname'];
              }
            
              Map<String, dynamic> toJson() {
                final Map<String, dynamic> data = new Map<String, dynamic>();
                data['name'] = this.name;
                data['surname'] = this.surname;
                return data;
              }
            }
lava
  • 6,020
  • 2
  • 31
  • 28
  • I/flutter (12520): ║ Instance of 'Future>' I/flutter (12520): I/flutter (12520): ╔╣ DioError ║ DioErrorType.other I/flutter (12520): ║ Converting object to an encodable object failed: Instance of 'Future>' – Codeguru Feb 25 '22 at 10:24
  • orjinal ---- var newL = RefundPostController.to.getReturn.map((value) => value.toJson()); var newList = newL.map((e) => RefundProductListData.fromJson(e)) .toList(); – Codeguru Feb 25 '22 at 10:24
  • I have successfully sent the data. thank you so much. – Codeguru Feb 25 '22 at 10:43
0

You can generate required Model automatically from JSON structure, you can use online generators e.g. quicktype.io, just paste your JSON, select dart language and generate your model.

3squad
  • 355
  • 3
  • 14
  • yes I know. There is no problem with the model. I'm sending the data from the "temporary" to the model with "toJson" on the "controller". The main model is not the list, but there is the model with the list in it. – Codeguru Feb 25 '22 at 09:00