【问题标题】:Problem converting data to json "type 'Null' is not a subtype of type 'String'" in Flutter将数据转换为 json 时出现问题 \"type \'Null\' is not a subtype of type \'String\'\" in Flutter
【发布时间】:2022-09-29 23:07:46
【问题描述】:

我有从服务器收到的数据。我通过了有 froJson, toJson 方法的模型。在 toJson 方法中,我遇到了问题。当我想将数据转换回 Json 时,出现错误(我附上了下面的屏幕截图)。告诉我如何解决这个问题,以便数据一切正常,我可以将它们转换为 Json?

主模型

class MainModel {
  String name;
  List<AmenitiesModel>? amenities;
  List<DeviceModel>? devices;
  List<PhotoModel>? photos;

  MainModel ({
    required this.name,
    this.amenities,
    this.devices,
    this.photos,
  });

  factory MainModel .fromJson(Map<String, dynamic> json) =>
      MainModel(
          id: json[\'id\'],
          name: json[\'name\'],
          amenities: json[\'amenities\'] != null
              ? List<AmenitiesModel>.from(
                  json[\'amenities\'].map(
                    (item) => AmenitiesModel.fromJson(item),
                  ),
                ).toList()
              : null,
          user: json[\'user\'] != null ? User.fromJson(json[\'user\']) : null,
          devices: json[\'devices\'] != null
              ? List<PublicChargingDeviceModel>.from(
                  json[\'devices\'].map(
                    (item) => DeviceModel.fromJson(item),
                  ),
                ).toList()
              : null,
          photos: json[\'gallery\'] != null
              ? List<PhotoModel>.from(
                  json[\'gallery\'].map(
                    (item) => PhotoModel.fromJson(item),
                  ),
                ).toList()
              : null);

  Map<String, dynamic> toJson() {
    return {
      \'name\': name,
      \'amenities\': amenities!.map((e) => e.toJson()).toList(),
      \'devices\': devices?.map((e) => e.toJson()).toList(),
      \'gallery\': photos?.map((e) => e.toJson()).toList(),
    };
  }

便利设施型号

class AmenitiesModel {
  String name;
  final String type;

  AmenitiesModel({required this.type, required this.name});

  factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
    return AmenitiesModel(
      type: json[\'type\'],
      name: json[\'name\'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (type == \'other\') \'name\': name,
      \'type\': type,
    };
  }

错误

    标签: flutter dart dart-null-safety


    【解决方案1】:

    读取地图可以返回 null,您可以在 null 情况下提供默认值,例如

    factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
      return AmenitiesModel(
        type: json['type']??"",
        name: json['name']??"",
      );
    }
    
    

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 1970-01-01
      • 2022-11-20
      • 2022-11-19
      • 2020-04-12
      • 2021-10-22
      • 2023-01-12
      • 1970-01-01
      • 2021-02-21
      相关资源
      最近更新 更多