Flutter开发答题应用时RadioListTile无选中UI反馈问题
单选按钮点击无选中态的原因与修复
- 语法层笔误:
CauHoiModel类的构造函数名与类名不匹配,类声明为CauHoiModel,但内部构造函数写为QuestionModel,属于无效的类实例化定义。 - 选中态失效的核心逻辑问题:Dart中自定义类默认的相等判断逻辑是对象引用地址相等。你在
itemBuilder中为每个选项设置的value都是build阶段临时新建的CauHoiModel实例,每次setState触发页面重绘时,itemBuilder会重新执行,生成全新的CauHoiModel对象作为Radio的value:哪怕第一次点击时把临时对象存进了_list作为groupValue,重绘后Radio的value已经变成了另一个全新的实例,和存下来的groupValue引用永远不一致,因此永远无法匹配出选中态。 - 冗余设计优化点:无需将整个
CauHoiModel作为Radio的选中值,仅存储选中的选项标识(即"A"/"B"字符串)即可完成状态匹配,既减少冗余对象创建的性能损耗,也从根源上规避自定义类的相等判断问题。
修复后的参考代码
首先修正模型类的构造函数笔误:
class CauHoiModel{ int id; String dapAn;//A, B, C, D // 修正构造函数名与类名保持一致 CauHoiModel({this.id, this.dapAn}); }
然后替换原RadioListTile的实现逻辑,直接用选项字符串作为状态匹配值:
RadioListTile( title: Text(widget.questions[index].ABCD.answerA.value), value: "A", groupValue: _list[index].dapAn, onChanged: (value) { setState(() { // 仅更新当前题的选中选项标识,无需替换整个模型对象 _list[index].dapAn = value as String; }); }, ), RadioListTile( title: Text(widget.questions[index].ABCD.answerB.value), value: "B", groupValue: _list[index].dapAn, onChanged: (value) { setState(() { _list[index].dapAn = value as String; }); }, ),
若坚持使用整个
CauHoiModel作为Radio的匹配值,必须在模型类中重写相等判断逻辑,否则不管怎么调整setState逻辑都无法触发选中态:// 补充在CauHoiModel类内部 @override bool operator ==(Object other) => identical(this, other) || other is CauHoiModel && runtimeType == other.runtimeType && id == other.id && dapAn == other.dapAn; @override int get hashCode => id.hashCode ^ dapAn.hashCode;
内容的提问来源于stack exchange,提问作者NamNguyen
相关产品推荐
相关产品推荐

