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

如何创建两行各4个选项的CustomRadioButton组件

解决方案

要实现两行各4个按钮且适配屏幕宽度,你可以拆分按钮列表为两组,用Column包裹两个CustomRadioButton组件,同时让每个组件占满屏幕宽度,自动均分按钮空间:

Column(
  children: [
    // 第一行:4个按钮
    CustomRadioButton(
      elevation: 0,
      absoluteZeroSpacing: true,
      unSelectedColor: Theme.of(context).canvasColor,
      buttonLables: ['1', '2', '3', '4'],
      buttonValues: ["1", "2", "3", "4"],
      buttonTextStyle: ButtonTextStyle(
        selectedColor: Colors.white,
        unSelectedColor: Colors.black,
        textStyle: TextStyle(fontSize: 16),
      ),
      radioButtonValue: (value) {
        print(value);
      },
      height: 50,
      width: MediaQuery.of(context).size.width, // 占满屏幕宽度
      selectedColor: Colors.red,
    ),
    // 第二行:4个按钮
    CustomRadioButton(
      elevation: 0,
      absoluteZeroSpacing: true,
      unSelectedColor: Theme.of(context).canvasColor,
      buttonLables: ['5', '6', '7', '8'],
      buttonValues: ["5", "6", "7", "8"],
      buttonTextStyle: ButtonTextStyle(
        selectedColor: Colors.white,
        unSelectedColor: Colors.black,
        textStyle: TextStyle(fontSize: 16),
      ),
      radioButtonValue: (value) {
        print(value);
      },
      height: 50,
      width: MediaQuery.of(context).size.width, // 占满屏幕宽度
      selectedColor: Colors.red,
    ),
  ],
)

关键修改点:

  • 将原8个按钮拆分为两组,分别放入两个CustomRadioButton组件
  • 给每个CustomRadioButton添加width: MediaQuery.of(context).size.width,让组件占满屏幕宽度,按钮会自动均分可用空间
  • 用Column替代原Row,实现上下两行的布局

如果需要保持8个按钮的单选逻辑(仅能选中一个),需维护全局选中状态,在两个组件的回调中同步更新,并通过defaultSelected属性同步选中状态:

// 定义状态变量
String? selectedValue;

// 在build方法中使用
Column(
  children: [
    CustomRadioButton(
      // ...其他属性
      defaultSelected: selectedValue,
      radioButtonValue: (value) {
        setState(() {
          selectedValue = value;
        });
      },
      // ...其他属性
    ),
    CustomRadioButton(
      // ...其他属性
      defaultSelected: selectedValue,
      radioButtonValue: (value) {
        setState(() {
          selectedValue = value;
        });
      },
      // ...其他属性
    ),
  ],
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:57:17