Map of object containing a List<Object> for sqlite

后端 未结 1 1186
误落风尘
误落风尘 2020-12-06 23:40

I am setting up my model classes to confirm to the docs for sqflite which suggest including a named constructor to convert to/from Maps to better handling of data between th

相关标签:
1条回答
  • 2020-12-07 00:30

    Here I am explaining the following

    1. How to convert a model object into Map to use with sqlite
    2. How to convert a Map object from sqlite into a model class.
    3. How to parse JSON reponse properly in flutter
    4. How to convert a model object into JSON

    All of the above questions has same answer. Dart has great support for these operations. Here I am going to illustrate it with a detailed example.

    class DoctorList{
      final List<Doctor> doctorList;
    
      DoctorList({this.doctorList});
    
      factory DoctorList.fromMap(Map<String, dynamic> json) {
        return DoctorList(
          doctorList: json['doctorList'] != null
              ? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
              : null,
        );
      }
    
      Map<String, dynamic> toMap() {
        final Map<String, dynamic> data = Map<String, dynamic>();
        if (this.doctorList != null) {
          data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
        }
        return data;
      }
    }
    

    The above DoctorList class has a member which holds a list of 'Doctor' objects..

    And see how I parsed the doctorList.

     doctorList: json['doctorList'] != null
          ? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
          : null,
    

    You may wonder, how the Doctor class may look like. Here you go

    class Doctor {
      final String doCode;
      final String doctorName;
    
      Doctor({this.doCode, this.doctorName});
    
      factory Doctor.fromMap(Map<String, dynamic> json) {
        return Doctor(
          doCode: json['doCode'],
          doctorName: json['doctorName'],
        );
      }
    
      Map<String, dynamic> toMap() {
        final Map<String, dynamic> data = Map<String, dynamic>();
        data['doCode'] = this.doCode;
        data['doctorName'] = this.doctorName;
        return data;
      }
    
    }
    

    That's all. Hope you got the idea. Cheers!

    0 讨论(0)
提交回复
热议问题