Dart空安全下setState闭包返回类型不匹配问题求解
Dart空安全下setState闭包返回类型错误解决方案
问题场景
使用版本范围>=2.12.0 <3.0.0的Dart空安全SDK时,执行代码中setState(() => controller.text = formattedDate);行出现错误:返回类型‘String’并非闭包上下文要求的‘Null’类型。
问题原因
setState接收的闭包属于VoidCallback类型,要求闭包没有返回值。而使用箭头函数=>时,右侧的赋值表达式controller.text = formattedDate会返回被赋予的formattedDate(String类型),不符合VoidCallback的类型要求,因此触发错误。
解决方案
将单行箭头函数改为代码块形式,明确闭包无返回值:
// 原错误代码 setState(() => controller.text = formattedDate); // 修改后代码 setState(() { controller.text = formattedDate; });
修改后的完整代码片段
@override Widget build(BuildContext context) { return GestureDetector( child: TextFormField( controller: controller, validator: (value) { if (value!.isEmpty) { return errorMessage; } return null; }, decoration: InputDecoration( hintText: hintText, suffixIcon: controller.text.length > 0 ? IconButton( onPressed: () { controller.clear(); }, icon: Icon(Icons.cancel, color: Colors.grey) ) : null, ), readOnly: true, onTap: () async { DateTime? pickedDate = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(1900), lastDate: DateTime(2040)); if (pickedDate != null) { print(pickedDate); String formattedDate = DateFormat('MMM d, yyyy').format(pickedDate); print(formattedDate); // 修改后的setState调用 setState(() { controller.text = formattedDate; }); } else { print("Date is not selected"); } }, ), ); }
内容的提问来源于stack exchange,提问作者Elly John Mirasol
相关产品推荐
相关产品推荐

