Flutter报错:返回类型'int'不符合闭包要求的'Null'类型求助
解决Flutter报错:“The return type 'int' isn't a 'Null', as required by the closure's context”
错误原因
- 你把
_SelectButton定义成了StatelessWidget,但它包含了需要动态修改的状态变量_value,StatelessWidget是无状态组件,本就不该维护可变状态。 - 你自定义的
setState方法要求传入的闭包返回Null,但你写的() => _value = 0是返回int的闭包(赋值表达式的返回值是等号右侧的数值,也就是0,类型为int),这直接导致了类型不匹配报错。
解决方案
方案一:改为StatefulWidget(推荐)
把组件改成StatefulWidget,使用Flutter内置的setState方法,这是处理组件状态变化的标准方式,能自动触发UI重建:
class _SelectButton extends StatefulWidget { @override State<_SelectButton> createState() => _SelectButtonState(); } class _SelectButtonState extends State<_SelectButton> { int _value = 0; @override Widget build(BuildContext context) { return BlocBuilder<SignUpCubit, SignUpState>( buildWhen: (previous, current) => previous.email != current.email, builder: (context, state) { return Padding( padding: const EdgeInsets.all(20.0), child: Row( children: <Widget>[ GestureDetector( onTap: () => setState(() => _value = 0), child: Container( height: 56, width: 56, color: _value == 0 ? Colors.grey : Colors.transparent, child: const Icon(Icons.call), ), ), const SizedBox(width: 4), GestureDetector( onTap: () => setState(() => _value = 1), child: Container( height: 56, width: 56, color: _value == 1 ? Colors.grey : Colors.transparent, child: const Icon(Icons.message), ), ), ], ), ); }, ); } }
方案二:修正自定义setState类型(不推荐)
如果非要用StatelessWidget(不建议,因为无法触发UI重建),可以修改自定义setState的参数类型,但点击按钮后UI不会更新,因为StatelessWidget不会主动重建:
class _SelectButton extends StatelessWidget { int _value = 0; @override Widget build(BuildContext context) { return BlocBuilder<SignUpCubit, SignUpState>( buildWhen: (previous, current) => previous.email != current.email, builder: (context, state) { return Padding( padding: const EdgeInsets.all(20.0), child: Row( children: <Widget>[ GestureDetector( onTap: () => setState(() => _value = 0), child: Container( height: 56, width: 56, color: _value == 0 ? Colors.grey : Colors.transparent, child: Icon(Icons.call), ), ), SizedBox(width: 4), GestureDetector( onTap: () => setState(() => _value = 1), child: Container( height: 56, width: 56, color: _value == 1 ? Colors.grey : Colors.transparent, child: Icon(Icons.message), ), ), ], ), ); }, ); } // 修改参数类型为接受任意返回值的闭包 void setState(Function() param0) { param0(); } }
额外提示
- 优先选方案一,StatefulWidget是Flutter专门设计用来处理有状态变化的组件,内置
setState会自动触发组件重建,确保UI和状态同步。 - 你的
buildWhen条件是对比前后状态的email,这和当前按钮的选择状态无关,如果不需要根据email变化重建按钮,可以考虑移除buildWhen,或者调整逻辑使其匹配需求。
内容的提问来源于stack exchange,提问作者Danyl Marie
相关产品推荐
相关产品推荐

