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
相关产品推荐
相关产品推荐

