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

Flutter天气组件报错排查:'DateTime?'参数类型不匹配问题

问题分析与解决方案

错误原因

报错源于Dart的空安全机制:weather.sunset和weather.sunrise是可空的DateTime?类型,但DateTime.isAfter()和DateTime.isBefore()方法要求传入非空的DateTime参数,类型不匹配导致报错。

修正后的代码

推荐使用安全的空值检查方式,避免运行时异常:

bool isNight(Weather weather) {
  final now = DateTime.now();
  final sunset = weather.sunset;
  final sunrise = weather.sunrise;

  // 若日出/日落时间未获取到,根据业务需求返回默认值(示例返回false)
  if (sunset == null || sunrise == null) {
    return false;
  }

  return now.isAfter(sunset) || now.isBefore(sunrise);
}

如果能确保接口一定会返回日出日落时间,也可以使用空断言(不推荐在不确定场景下使用,否则null时会触发崩溃):

bool isNight(Weather weather) {
  final now = DateTime.now();
  return now.isAfter(weather.sunset!) || now.isBefore(weather.sunrise!);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:27:00