Flutter中TextField触发setState致Radio选中状态重置问题求助
问题原因
你把currentOption的初始化写在了build方法内部,每次调用setState都会重新执行build,导致currentOption被强制重置为options[0]。所以点击TextField触发状态更新时,选中项就自动回到第一项了。
解决方法
1. 调整状态变量的位置
把currentOption和选项列表options移到State类的成员变量区域,不要放在build方法里。这样变量值会在组件生命周期中保持,不会每次build都被重置。
2. 修正后的完整代码示例
class YourSheetScreen extends StatefulWidget { @override _YourSheetScreenState createState() => _YourSheetScreenState(); } class _YourSheetScreenState extends State<YourSheetScreen> { // 把选项和选中状态作为State成员变量 final List<String> options = ["A", "B", "C", "D", "Others"]; String currentOption = "A"; // 初始选中第一项 @override Widget build(BuildContext context) { return DraggableScrollableSheet( builder: (context, scrollController) { return SingleChildScrollView( controller: scrollController, child: Column( children: [ // 用循环生成所有RadioListTile,避免重复代码 for (final option in options) RadioListTile( activeColor: Colors.red, title: Text(option), value: option, groupValue: currentOption, onChanged: (value) { setState(() { currentOption = value as String; }); }, ), // 显示TextField的判断逻辑 if (currentOption == options.last) TextField( decoration: InputDecoration( hintText: "请输入其他内容", border: OutlineInputBorder(), ), // 如果需要保存输入内容,可添加单独的状态变量 // String _otherInput = ""; // onChanged: (text) { // setState(() { // _otherInput = text; // }); // }, ) else SizedBox(height: 16), ], ), ); }, ); } }
额外优化点
- 用循环遍历选项生成RadioListTile,不用重复写5次组件,代码更简洁。
- 用
options.last代替options[4],如果后续选项数量变化,代码不用修改。 - 若需要保存TextField的输入内容,单独定义一个状态变量(比如
_otherInput),和currentOption分开管理,避免状态冲突。
内容的提问来源于stack exchange,提问作者Victor Woode
相关产品推荐
相关产品推荐

