Flutter中已将selectedGender设为可空,setState仍无法更新卡片颜色?
问题原因及解决方案
1. 点击卡片无法切换选中状态的核心问题
你在onTap的setState回调里误用了相等比较运算符==,而不是赋值运算符=:
// 错误写法:仅做相等判断,未修改变量值 selectedGender == Gender.male; // 正确写法:赋值更新状态 selectedGender = Gender.male;
因为没有实际修改selectedGender的取值,setState触发组件重建后,selectedGender == Gender.male的判断结果仍为初始的false,所以卡片颜色不会切换为选中状态。
2. 使用late修饰触发LateInitializationError的原因
late关键字的作用是告知Dart:该变量会在首次被访问前完成初始化。但你用late Gender selectedGender;声明后,并未在build方法执行前给变量赋值,而build过程中会立刻执行selectedGender == Gender.male的判断——此时变量还未被初始化,直接访问就会抛出LateInitializationError。
修复后的关键代码片段
class _InputPageState extends State<InputPage>{ Gender? selectedGender; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: mainColor, appBar: AppBar( title: Text('BMI Calculator'), backgroundColor: Colors.transparent, elevation: 0, centerTitle: true, ), body: Column( children: <Widget>[ Expanded( child: Row( children: [ Expanded( child: GestureDetector( child: ReusableCard( colour: selectedGender == Gender.male ? activeCardColor : inactiveCardColor, cardChild: IconContent( icon: FontAwesomeIcons.mars, label: 'MALE', ), ), onTap: (){ setState(() { // 修正为赋值运算符,更新选中状态 selectedGender = Gender.male; }); }, ), ), // 女性卡片可同理设置:selectedGender = Gender.female ], ), ), // 剩余代码省略 ], ), ); } }
内容的提问来源于stack exchange,提问作者Elle Bishop
相关产品推荐
相关产品推荐

