Flutter:如何获取AlertDialog内RadioButtonFormField的选中值?
你可以通过两种方式实现需求,既不用直接返回首页,又能拿到单选按钮的选中值:
1. 弹窗内实时获取并处理选中值
利用StatefulBuilder给AlertDialog的内容区域添加局部状态,这样单选按钮切换时就能实时更新并获取值,不需要关闭弹窗:
// 首页打开弹窗的代码 showDialog( context: context, builder: (context) { bool _selectedBool = false; // 初始选中值 return AlertDialog( title: const Text('设置布尔值'), content: StatefulBuilder( builder: (context, setState) { return RadioButtonFormField( value: _selectedBool, onChanged: (newValue) { setState(() { _selectedBool = newValue!; }); // 在这里实时处理选中值,比如打印、调用业务方法 print('当前选中:$_selectedBool'); }, options: const [ RadioOption(label: '开启', value: true), RadioOption(label: '关闭', value: false), ], ); }, ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('取消'), ), TextButton( onPressed: () { // 确认时可以做最终处理,比如保存值 Navigator.pop(context); }, child: const Text('确认'), ), ], ); }, );
2. 关闭弹窗时将选中值传回首页
通过Navigator.pop(context, 返回值)的方式,把选中值作为参数带回首页,首页通过await或then接收:
// 首页打开弹窗并接收返回值 final result = await showDialog<bool>( context: context, builder: (context) { bool _selectedBool = false; return AlertDialog( title: const Text('设置布尔值'), content: StatefulBuilder( builder: (context, setState) { return RadioButtonFormField( value: _selectedBool, onChanged: (newValue) { setState(() { _selectedBool = newValue!; }); }, options: const [ RadioOption(label: '开启', value: true), RadioOption(label: '关闭', value: false), ], ); }, ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('取消'), ), TextButton( onPressed: () => Navigator.pop(context, _selectedBool), child: const Text('确认'), ), ], ); }, ); // 首页处理返回值 if (result != null) { print('弹窗返回的布尔值:$result'); // 执行后续业务逻辑,比如保存到本地、更新页面状态 }
自定义RadioButtonFormField的参考实现
确保你的自定义组件能正确传递选中值:
class RadioButtonFormField extends StatelessWidget { final bool value; final ValueChanged<bool?>? onChanged; final List<RadioOption> options; const RadioButtonFormField({ super.key, required this.value, required this.onChanged, required this.options, }); @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: options.map((option) { return RadioListTile<bool>( title: Text(option.label), value: option.value, groupValue: value, onChanged: onChanged, ); }).toList(), ); } } class RadioOption { final String label; final bool value; const RadioOption({required this.label, required this.value}); }
内容的提问来源于stack exchange,提问作者UprightSleepy
相关产品推荐
相关产品推荐

