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

Flutter实现:将两个固定尺寸Container置于Row均分列的居中位置

Flutter实现Row两等列且子Container居中的解决方案

问题场景

我有两个设置了固定宽高和背景色的Container(小型黄色方块),需要将它们放置在父容器的Row中,要求Row被分为两等列,每个Container位于各自列的居中位置。

  • 预期效果:两个黄色小方块分别处于Row左右两个等分区域的中心
  • 当前问题:直接将两个Widget放在Row中会挤在一起;使用Expanded但未嵌套居中组件时,Container会被拉伸占满可用空间

当前代码

Row代码

Row(
  children: [
    SwitchPreviewButton(),
    
    SwitchPreviewButton(),
  ],
);

SwitchPreviewButton代码

Widget build(BuildContext context) {
  double width = 10.22;
  double height = 17.32;

  return Container(
    constraints: BoxConstraints(maxWidth: width, maxHeight: height),
    width: width,
    height: height,
    decoration: BoxDecoration(
      color: Colors.yellow,
      borderRadius: BorderRadius.circular(1.16)
    ),
  );
}

解决方案

只需要修改Row的结构,给每个SwitchPreviewButton外层嵌套Expanded和Center组件:

Row(
  children: [
    Expanded(
      child: Center(child: SwitchPreviewButton()),
    ),
    Expanded(
      child: Center(child: SwitchPreviewButton()),
    ),
  ],
);

原理说明

  • Expanded:让两个子项平分Row的全部可用宽度,实现"两等列"的布局要求
  • Center:作为Expanded的子组件,让内部的SwitchPreviewButton在当前等分区域内水平、垂直居中,同时保留Container自身的固定宽高,不会被拉伸变形

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:20:05