来自子类中的 json 方法

From json method in subclasses

我有一个基础 class 喜欢:

class TransportationVehicle {
   String name;
   
   TransportationVehicle(this.name);
   
   Map<String, dynamic> toJson() {
       final Map<String, dynamic> data = <String, dynamic>{};
       data['name'] = name;
       return data;
     }
 }

还有多个子class喜欢:

class Bike extends TransportationVehicle {
   int pedals;
   
   Bike(String name, this.pedals) : super(name);
   
   @override
   Map<String, dynamic> toJson() {
     final data = super.toJson();
     data['pedals'] = pedals;
     return data;
    }
}

有了它,我可以将不同类型的列表转换为 json 字符串。但这如何与 fromJson 功能一起使用?

您可以通过使用基础 class.

来使用与 toJson() 方法相同的想法
import 'dart:convert';

class TransportationVehicle {
  final String? name;

  TransportationVehicle({
    this.name,
  });

  factory TransportationVehicle.fromRawJson(String str) =>
      TransportationVehicle.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory TransportationVehicle.fromJson(dynamic json) => TransportationVehicle(
        name: json['name'] == null ? null : json['name'] as String,
      );

  Map<String, dynamic> toJson() => {
        'name': name == null ? null : name,
      };
}

class Bike extends TransportationVehicle {
  final int? pedals;

  Bike({
    String? name,
    this.pedals,
  }) : super(name: name);

  factory Bike.fromRawJson(String str) => Bike.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Bike.fromJson(dynamic json) {
    TransportationVehicle vehicle = TransportationVehicle.fromJson(json);
    return Bike(
      name: vehicle.name == null ? null : vehicle.name,
      pedals: json['pedals'] == null ? null : json['pedals'] as int,
    );
  }

  Map<String, dynamic> toJson() {
    final data = super.toJson();
    data['pedals'] = pedals == null ? null : pedals;
    return data;
  }
}