我当前正在尝试显示一个引用多个其他类但可以为空的类,因为它并不总是确定哪个引用的类具有值。现在,由于
Dart
积极尝试加载您在模型类中声明的所有必需内容,它想要加载可空类的所有字段,而我真的不想这样做。我可以做什么来限制这种行为?当我必须自己处理那些引用的类时,这还好,但这一次真的很烦人,因为我已经将它们设置为可为空,并且它们仍在尝试加载。
这是我到目前为止的代码:
这是我在问题中提到的模型:
import 'package:json_annotation/json_annotation.dart';
part 'delivery.g.dart';
enum DeliveryStatus {
@JsonValue(0)ToBeConfirmed,
@JsonValue(1)Ongoing,
@JsonValue(2)Received,
@JsonValue(3)Cancelled,
}
@JsonSerializable(explicitToJson: true)
class Delivery{
Delivery({
this.id,
this.shippingDoc,
this.shippingDocId,
this.vhc,
this.vhcId,
this.aic,
this.aicId,
required this.status,
required this.receivedOnDatetime,
this.receivedBy,
required this.receivedById,
this.remarks,
this.isConfirmed,
this.isCancelled,
this.confirmedOnDatetime,
this.cancelledOnDatetime,
});
@JsonKey(name: 'id')
String? id = "";
@JsonKey(name: 'shipping_doc')
ShippingDoc? shippingDoc;
@JsonKey(name: 'shipping_doc_id')
String? shippingDocId = "";
@JsonKey(name: 'vhc')
VhcApplication? vhc;
@JsonKey(name: 'vhc_id')
String? vhcId = "";
@JsonKey(name: 'aic')
VhcApplication? aic;
@JsonKey(name: 'aic_id')
String? aicId = "";
@JsonKey(name: 'status')
DeliveryStatus status = DeliveryStatus.ToBeConfirmed;
@JsonKey(name: 'received_on_datetime')
String receivedOnDatetime = '';
@JsonKey(name: 'received_by')
User? receivedBy;
@JsonKey(name: 'received_by_id')
String receivedById = "";
@JsonKey(name: 'remarks')
String? remarks = "";
@JsonKey(name: 'is_confirmed')
bool? isConfirmed = false;
@JsonKey(name: 'is_cancelled')
bool? isCancelled = false;
@JsonKey(name: 'confirmed_on_datetime')
String? confirmedOnDatetime = "";
@JsonKey(name: 'cancelled_on_datetime')
String? cancelledOnDatetime = "";
factory Delivery.fromJson(Map<String, dynamic> json) => _$DeliveryFromJson(json);
Map<String, dynamic> toJson() => _$DeliveryToJson(this);
}
引用的类是ShippingDoc VhcApplication和VhcApplication(我还没有实现aic的真正类)。现在,ShippingDoc 很有价值,因为我拥有了它。另一方面,VhcApplication 是并且应该为 null,并且是导致问题的原因,因为它为 null 但
Dart
仍然想要加载它的字段
您可以更新 JsonKey 注释并使用
includeFromJson: false
和/或 includeToJson: false
像这样:
@JsonKey(includeFromJson: false, includeToJson: false)
VhcApplication? vhc;
参考: https://pub.dev/documentation/json_annotation/4.9.0/json_annotation/JsonKey-class.html