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

Flutter如何在Row中添加TextField与Radio按钮并解决布局报错

问题原因

你遇到的hasSize断言报错核心是Flutter布局过程中Flex类组件(Row/Column/Flexible)的尺寸计算规则冲突,具体错误点有3处:

  • Flexible组件只能作为Row、Column、Flex这三类Flex容器的直接子组件使用,你的代码中存在SizedBox嵌套Flexible、Flexible嵌套SizedBox的写法,导致Flexible无法和上级Column通信获取伸缩空间分配规则,布局尺寸无法计算。
  • 放在Row中的Column没有指定固定宽度,Row的主轴为水平方向,未指定宽度的Column无法确定自身水平方向占位尺寸,最终引发布局计算失败。
  • 额外的写法错误:你在Column(主轴为垂直方向)中使用SizedBox(width: 10)做间距,该写法无法产生垂直空隙,反而会增加无意义的布局节点。
解决方法

按以下步骤修改代码即可修复报错:

  1. 给Row内的Column外层包裹一个指定宽度的SizedBox/Container,明确Column的水平占位尺寸
  2. 删掉所有不必要的Flexible嵌套,你的Radio和Text都是固定尺寸组件,不需要伸缩能力
  3. 将Column内的间距组件改为SizedBox(height: 10),实现垂直方向的间距效果

修正后的核心代码参考:

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Material(
      elevation: 30.0,
      shadowColor: Colors.grey,
      child: SizedBox(  
        width: 300,
        child: TextField(
          controller: heightcon,
          style: TextStyle(
            color: Colors.black,
            fontSize: 30,
          ),
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'Height',
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(0.0),
              borderSide: BorderSide(
                color: Colors.black,
                width: 2.0,
              ),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(0.0),
              borderSide: BorderSide(
                color: Colors.black54,
                width: 2.0,
              ),
            ),
          ),
          onChanged: (heightval) {
            print('First text field: $heightval');
            globals.heightvalue = double.parse(heightval);
          },
        ),
      ),
    ),
    // 给Column指定固定宽度
    SizedBox(
      width: 80,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Radio(
            value: 1,
            groupValue: 1,
            onChanged: (value) {},
          ),
          // 垂直间距用height属性设置
          SizedBox(height: 4,),
          Text("Radio 1"),
          SizedBox(height: 10,),
          Radio(
            value: 2,
            groupValue: 1,
            onChanged: (value) {},
          ),
          SizedBox(height: 4,),
          Text("Radio 2")
        ],
      ),
    ),
  ],
),

提示:如果要实现两个Radio的单选效果,需要给两个Radio设置不同的value属性,同时将groupValue绑定到同一个可修改的状态变量上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:24:00