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

Flutter使用showTimePicker时给selectedTime的hour赋值报错如何解决

报错原因

TimeOfDay是Flutter内置的不可变类,它的hour、minute属性均被final关键字修饰,仅支持读取取值,不支持直接修改赋值,因此尝试给selectedTime.hour赋值的操作不符合语法规范,触发报错。

解决方法

有两种可行的修复方案,可根据你的业务需求选择:

  • 方案1:直接替换整个selectedTime对象
    如果不需要保留原有selectedTime的属性值,直接将用户选择返回的_time完整赋值给selectedTime即可,修改后的代码如下:
TimeOfDay selectedTime = TimeOfDay.now();

IconButton(
  icon: Icon(Icons.access_time, color: Colors.blue),
  onPressed: () async {
    TimeOfDay? _time = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (_time != null) {
      selectedTime = _time;
    }
  },
),
  • 方案2:使用copyWith方法生成新对象
    如果你仅需要修改hour属性,保留原有selectedTime的minute值,可以调用TimeOfDay自带的copyWith方法生成新对象再赋值:
if (_time != null) {
  selectedTime = selectedTime.copyWith(hour: _time.hour);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:48:00