Flutter 2.2.3版本Date Picker运行报错 可空类型赋值异常问题咨询
报错产生原因
你所用的Flutter 2.2.3版本对应Dart 2.13.4,默认开启了空安全特性。Flutter官方对showDatePicker方法的返回值做了适配:当用户点击日期选择器的取消按钮时,方法会返回null,因此返回类型从旧版非空的DateTime调整为可空的DateTime?。你声明的picked变量为非空DateTime类型,直接接收可能为null的返回值就会触发类型不匹配的编译错误。
修复方案
推荐优先使用判空处理的方案,兼顾安全性和业务合理性:
DateTime selectedDate = DateTime.now(); Future<void> _selectDate(BuildContext context) async { // 将picked声明为可空类型 final DateTime? picked = await showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2021, 1, 1), lastDate: DateTime(2022, 1, 1), ); // 仅当用户选中了有效日期时才更新状态 if (picked != null) { setState(() { selectedDate = picked; }); } }
也可以根据业务场景选择其他方案:
- 如果业务要求必须选中日期,可使用空断言
!强制转换类型(不推荐,若返回null会触发运行时崩溃):final DateTime picked = await showDatePicker(/*参数不变*/)!; - 如果未选中时需要使用默认值,可使用空判断运算符
??设置兜底值:// 未选中时默认用当前已选的selectedDate final DateTime picked = await showDatePicker(/*参数不变*/) ?? selectedDate;
内容的提问来源于stack exchange,提问作者Soundhar Raj
相关产品推荐
相关产品推荐

