使用form_bloc与CupertinoDatePicker时出现返回null错误求解决
解决form_bloc中CupertinoDatePicker的非空返回值错误
错误核心原因:DateTimeField的onShowPicker回调要求返回Future<DateTime?>类型,但你的代码既没有返回值,也未正确处理日期选择后的结果传递,同时存在几处语法错误,导致类型不匹配。
以下是具体修正步骤及完整代码:
修正
onShowPicker的返回逻辑:onShowPicker必须返回一个Future<DateTime?>,所以要直接返回showCupertinoDialog的执行结果,在用户确认选择后返回选中的日期,取消时返回null。修复代码中的语法错误:
- 将
initialDateTime: value改为initialDateTime: currentValue,使用回调传入的当前值作为初始日期 inputFieldBloc.updateValue必须传入选中的日期参数,不能只写方法名- 移除
setState,form_bloc会自动管理状态更新,无需手动调用
- 将
完整修正后的代码:
Widget build(BuildContext context) { return BlocBuilder<InputFieldBloc, InputFieldBlocState>( bloc: inputFieldBloc, builder: (context, state) { return DateTimeField( format: DateFormat("dd-MM-yyyy"), initialValue: state.value, resetIcon: null, onChanged: (value) { inputFieldBloc.updateValue(value); }, onShowPicker: (context, currentValue) async { DateTime? selectedDate; await showCupertinoDialog( context: context, builder: (context) => CupertinoAlertDialog( content: CupertinoDatePicker( initialDateTime: currentValue ?? DateTime.now(), mode: CupertinoDatePickerMode.date, use24hFormat: true, onDateTimeChanged: (value) { selectedDate = value; }, ), actions: [ CupertinoDialogAction( child: const Text('确定'), onPressed: () { Navigator.pop(context); }, ), CupertinoDialogAction( child: const Text('取消'), onPressed: () { selectedDate = null; Navigator.pop(context); }, ), ], ), ); if (selectedDate != null) { inputFieldBloc.updateValue(selectedDate); } return selectedDate; }, decoration: InputDecoration( labelText: labelText, prefixIcon: const Icon(Icons.calendar_today), border: const OutlineInputBorder(), ), ); }, ); }
内容的提问来源于stack exchange,提问作者1988
相关产品推荐
相关产品推荐

