将切换按钮扩展到父容器宽度

Lon*_*olf 5 dart flutter

有什么方法可以在不进行任何硬编码的情况下将切换按钮动态扩展到父容器宽度。我找到了一个使用 MediaQuery 上下文的答案,该答案仅适用于全屏宽度。我还尝试将按钮包装在展开的小部件中,但这会引发错误

Container(
  width: 150.0, // hardcoded for testing purpose 
  child: ToggleButtons(
    constraints:
        BoxConstraints.expand(width: MediaQuery.of(context).size.width), // this doesn't work once inside container unless hard coding it
    borderRadius: BorderRadius.circular(5),
    children: [
      ShapeToggleButton(
        text: 'Option1',
      ),
      ShapeToggleButton(
        text: 'Option2',
      ),
    ],
    isSelected: [true, false],
    onPressed: (index) {},
  ),
);
Run Code Online (Sandbox Code Playgroud)

Lon*_*olf 17

正如 psink 在上面的评论中所建议的,答案是将它包装在 LayoutBuilder 中

        Container(
              width: 150.0, // hardcoded for testing purpose
              child: LayoutBuilder(builder: (context, constraints) {
        return ToggleButtons(
          renderBorder: false,
          constraints:
              BoxConstraints.expand(width: constraints.maxWidth / 2), //number 2 is number of toggle buttons
          borderRadius: BorderRadius.circular(5),
          children: [
            Text(
              'Option1',
            ),
            Text(
              'Option2',
            ),
          ],
          isSelected: [true, false],
          onPressed: (index) {},
        );
      })))
Run Code Online (Sandbox Code Playgroud)

  • 如果要渲染边框,还应该减去边框的权重 * 3(开始、中间和结束,假设您只有两个子元素),以避免右侧溢出 (5认同)