Flutter,当value为null时如何在DateTime.parse中返回空字符串

ldxq2e6h  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(136)

我传递了一个json到一个类构造函数中,有一个datetime字段,但有时返回值可能为null,当值为null时,我是否显示一个空字符串?

class dataRecord {
  int id;
  DateTime createdate;
  DateTime? confirmdate;

  dataRecord({
    required this.id,
    required this.createdate,
    this.confirmdate,
  });

  factory dataRecord.fromJson(Map<String, dynamic> json) {
    return dataRecord(
      id: json['id'] as int,
      createdate: DateTime.parse(json['createtime']) as DateTime,
      confirmdate: DateTime.parse(json['confirmtime']) as DateTime,
    );
  }
}

我尝试了DateTime.tryParse,但也不能让它工作。

fjaof16o

fjaof16o1#

您不能为字段返回空字符串,因为您已经将数据类型声明为DateTime?,但您可以返回null。用下面的类替换你的类。

class DataRecord {
  int id;
  DateTime createdate;
  DateTime? confirmdate;

  DataRecord({
    required this.id,
    required this.createdate,
    this.confirmdate,
  });

  factory DataRecord.fromJson(Map<String, dynamic> json) {
    return DataRecord(
      id: json['id'] as int,
      createdate: DateTime.parse(json['createtime']),
      confirmdate: json['confirmtime'] != null
          ? DateTime.parse(json['confirmtime'])
          : null,
    );
  }
}

相关问题