You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter RadioListTile多选问题及取值格式修正求助

解决Flutter RadioListTile的两个问题

问题1:无法实现单选(允许多选)

每个OptionsCard单独维护groupedValue状态,导致所有RadioListTile分属不同选项组,自然支持多选。

修复方案

将选项组的选中状态(groupedValue)提升到父组件,让所有OptionsCard共享同一状态,通过回调同步更新:

修改后的OptionsCard组件代码

class _OptionsCardState extends State<OptionsCard> {
  @override
  Widget build(BuildContext context) {
    return Card(
      color: AppColors.lightBlue,
      child: RadioListTile<String>(
        title: Text(widget.option),
        // 同时修复问题2:去掉大括号包裹,直接传递原字符串
        value: widget.option,
        groupValue: widget.groupValue,
        onChanged: (value) {
          widget.onChangeSelectedInput!(value ?? "");
        },
      ),
    );
  }
}

// 同步更新OptionsCard的外部类定义,新增groupValue参数
class OptionsCard extends StatefulWidget {
  final String option;
  final Color color;
  final String groupValue;
  final Function(String) onChangeSelectedInput;

  const OptionsCard({
    Key? key,
    required this.option,
    required this.color,
    required this.groupValue,
    required this.onChangeSelectedInput,
  }) : super(key: key);

  @override
  State<OptionsCard> createState() => _OptionsCardState();
}

修改后的父组件调用代码

// 父组件中维护全局的选中状态
String? _selectedOption = "";

// ...

for(var item in _questions[index].options!) OptionsCard(
  option: item,
  color: Colors.black,
  // 传递共享的选中状态
  groupValue: _selectedOption ?? "",
  onChangeSelectedInput: (String value) {
    setState(() {
      // 在父组件更新选中状态,同步所有OptionsCard
      _selectedOption = value;
    });
    debugPrint("selected ${value}"); // 现在输出纯字符串
  },
)

问题2:选中值带大括号

原因是RadioListTile的value被手动用大括号包裹:"{${widget.option}}",直接改为value: widget.option即可传递原始纯字符串,打印结果就不会带大括号。


内容的提问来源于stack exchange,提问作者ibramazin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:22:09