Flutter中使用TimePicker显示HH:mm格式时间遇格式异常问题排查
问题排查:Flutter TimePicker时间格式化异常
异常原因
你触发的FormatException是因为错误地将TimeOfDay的toString()结果传入DateFormat.parse()方法。TimeOfDay.toString()返回的是类似TimeOfDay(00:30)的字符串,完全不符合HH:mm的格式规则,导致解析失败。
原代码问题点
// 错误逻辑:用TimeOfDay.toString()的非标准格式去解析HH:mm closingTime = DateFormat('HH:mm') .parse(_toTime.toString()) .toString();
正确解决方案
方案1:利用TimeOfDay自带的format方法
你已经在showTimePicker的builder中设置了alwaysUse24HourFormat: true,直接调用_toTime.format(context)就能得到24小时制的HH:mm格式字符串:
setState(() { _toTime = value!; closingTime = _toTime.format(context); print('CLOSING TIME: $closingTime'); });
方案2:手动拼接小时和分钟(不依赖context配置)
如果需要脱离MediaQuery的24小时制设置限制,可以手动处理补零逻辑:
setState(() { _toTime = value!; String hourStr = _toTime.hour.toString().padLeft(2, '0'); String minuteStr = _toTime.minute.toString().padLeft(2, '0'); closingTime = '$hourStr:$minuteStr'; print('CLOSING TIME: $closingTime'); });
内容的提问来源于stack exchange,提问作者coolhack7
相关产品推荐
相关产品推荐

