Flutter调试控制台报'type 'Null' is not a subtype of type 'int'错误求助
解决Firestore时间戳转DateTime时的空类型错误
错误原因很明确:snapshot.data?.get("TimeToStart")可能返回null,或返回值不是int类型,而DateTime.fromMillisecondsSinceEpoch必须接收int类型参数,因此触发了类型不匹配的报错。你之前尝试用?? ""返回字符串,反而会引发更严重的类型问题——字符串无法作为int参数传入时间转换方法。
修复方案
- 先判断
deptTime是否为有效的int值,否则显示占位文本或使用默认时间戳 - 通过null安全的条件判断,避免空值或非int值传入时间转换逻辑
修复后的代码示例
// 在StreamBuilder内部 final deptTime = snapshot.data?.get("TimeToStart"); String startTime; // 校验是否为有效int值,再处理转换 if (deptTime is int) { startTime = DateFormat("hh:mm a").format(DateTime.fromMillisecondsSinceEpoch(deptTime)); } else { // 空值或非int时显示占位文本 startTime = "--:--"; } // 也可以用更简洁的三元表达式写法 final startTime = (deptTime is int) ? DateFormat("hh:mm a").format(DateTime.fromMillisecondsSinceEpoch(deptTime)) : "--:--"; // 渲染Text组件 Text(startTime)
如果业务允许用默认时间替代空值,也可以直接给deptTime设置默认int值:
final deptTime = snapshot.data?.get("TimeToStart") ?? 0; final startTime = DateFormat("hh:mm a").format(DateTime.fromMillisecondsSinceEpoch(deptTime));
这种方式会把空值转为0(对应1970-01-01的时间),但更推荐用占位文本的方式,避免用户看到无意义的默认时间。
内容的提问来源于stack exchange,提问作者Victor Woode
相关产品推荐
相关产品推荐

