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

Flutter单选按钮选中状态异常及文本框显示问题求助

问题分析与解决方案

问题根源

  1. Yes单选按钮无选中状态:点击Yes时,handleSelection只更新了_selectyes,但RadioListTile的groupValue绑定的是_medicalhistory,两者未同步,导致单选按钮无法触发选中样式。
  2. 选No时文本框不隐藏:点击No时没有重置控制文本框显示的_yes变量,且_yes的判断逻辑冗余,完全可以直接通过_medicalhistory的值来控制。

修正后的代码

简化变量和处理逻辑,去掉多余的_selectyes和_yes,直接用_medicalhistory管理选中状态和文本框显示:

// 初始化选中状态变量
late String? _medicalhistory;

Container(
  width: MediaQuery.of(context).size.width > 800
      ? 700
      : MediaQuery.of(context).size.width,
  padding: const EdgeInsets.all(20),
  child: Column(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Container(
        margin: const EdgeInsets.only(bottom: 20, top: 20),
        child: LinearPercentIndicator(
          padding: const EdgeInsets.symmetric(horizontal: 0.0),
          lineHeight: 20.0,
          animationDuration: 3000,
          percent: _completionPercentage,
          animateFromLastPercent: true,
          center: Text(
            "$_stepno/1",
            style: const TextStyle(color: Colors.white),
          ),
          barRadius: const Radius.circular(5),
          backgroundColor: Colors.grey,
          progressColor: Colors.black,
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "Past medical history: ",
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          RadioListTile(
            title: const Text("Yes"),
            value: "yes",
            groupValue: _medicalhistory,
            onChanged: (value) {
              setState(() {
                _medicalhistory = value.toString();
              });
            },
          ),
          // 直接通过_medicalhistory的值判断是否显示文本框
          if (_medicalhistory == "yes")
            const TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: 'Enter a search term',
              ),
            ),
          RadioListTile(
            title: const Text("No"),
            value: "no",
            groupValue: _medicalhistory,
            onChanged: (value) {
              setState(() {
                _medicalhistory = value.toString();
              });
            },
          ),
        ],
      )
    ],
  ),
)

关键改动说明

  • 移除冗余的_selectyes和_yes变量,只用_medicalhistory管理单选组的选中状态
  • 统一Yes和No单选按钮的onChanged逻辑,点击时直接更新_medicalhistory,保证单选按钮选中状态正常触发
  • 文本框显示条件改为_medicalhistory == "yes",选No时_medicalhistory变为"no",文本框自动隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:47:22