【问题标题】:Flutter - Unhandled Exception: Unhandled error type 'int' is not a subtype of type 'DateTime?'Flutter - 未处理的异常:未处理的错误类型“int”不是“DateTime”类型的子类型?
【发布时间】:2022-01-04 18:43:38
【问题描述】:

我正在使用 Freezed 和 json_annotation 来序列化 API 对象。

@freezed
class Block with _$Block {
  const factory Order({
    @JsonKey(name: 'block_id') required String id,
    @JsonKey(name: 'sent_at') DateTime? sentAt,
    @JsonKey(name: 'created_at') DateTime? createdAt,
  }) = _Block;

  factory Block.fromJson(Map<String, dynamic> json) => _$BlockFromJson(json);
}

但有时,API 返回错误的类型,在这种情况下,是 int 而不是 string,这会导致错误。 如果 createdAt 接收到错误的类型而不是抛出错误,有没有办法将它设置为 null?

【问题讨论】:

    标签: json flutter freezed


    【解决方案1】:

    听起来你的 createdAt 可能是 MillisecondsSinceEpoch。

    通常最好确保您的数据类型始终相同,但如果您的数据源未知,那么最好的选择可能是同时排除数据类型并稍后进行排序。

    @JsonKey(name: 'created_at') DateTime?|int? createdAt,

    if(createdAt is DateTime){
      //do something
    } else if(createdAt is int){
      //do something
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多