You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:DateTime.parse遇null时如何返回空字符串

解决JSON中日期字段为null时显示空字符串的问题

一、修复fromJson方法,安全处理null日期字段

你当前的fromJson方法直接调用DateTime.parse处理可能为null的confirmtime,会导致空值解析报错。需要先判断字段是否为null,再结合DateTime.tryParse做安全解析:

class DataRecord { // 遵循Dart规范,类名首字母大写
  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']), // createtime为必填字段,直接解析
      // 处理可空的confirmtime:先判断是否为null,非null时用tryParse(解析失败返回null)
      confirmdate: json['confirmtime'] != null 
          ? DateTime.tryParse(json['confirmtime']) 
          : null,
    );
  }
}

二、UI显示时将null转为空字符串

在需要展示confirmdate的地方,使用空值合并运算符??将null替换为空字符串:

1. 直接显示原始日期字符串

Text(dataRecord.confirmdate?.toString() ?? '')

2. 格式化日期后显示(需依赖intl包)

如果需要自定义日期格式,先在pubspec.yaml中添加intl依赖,再使用DateFormat处理:

import 'package:intl/intl.dart';

// 示例:格式化为yyyy-MM-dd HH:mm:ss
Text(dataRecord.confirmdate != null 
    ? DateFormat('yyyy-MM-dd HH:mm:ss').format(dataRecord.confirmdate!) 
    : '')

关键说明

  • DateTime.tryParse相比parse更安全:parse在输入无效时会抛出异常,tryParse会返回null,适配不确定的输入场景。
  • 遵循Dart代码规范:类名首字母大写,提升代码可读性和团队协作效率。

内容的提问来源于stack exchange,提问作者Tony Lam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:02:44