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

Flutter中如何将Row内的两个Container分别定位在左上和右上?

解决方案:实现Row内容器的左上/右上对齐

嘿,刚入门Flutter的话,布局这块确实得慢慢摸索~你要实现的红色容器左上、蓝色容器右上的效果其实很容易搞定,给你两种常用的方案:

方案1:通过Row的对齐属性直接控制

只需要给Row添加两个关键属性,就能精准控制子组件的位置:

class MyRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Row(
            // 水平方向两端对齐,让红色容器靠左,蓝色容器靠右
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            // 垂直方向顶部对齐,确保容器处于Row的左上/右上位置(而非默认垂直居中)
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.red,
              ),
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

关键属性解释:

  • mainAxisAlignment: MainAxisAlignment.spaceBetween:Row的主轴是水平方向,这个属性会让子组件在水平空间上两端对齐,中间自动填充空白,完美实现左右分布。
  • crossAxisAlignment: CrossAxisAlignment.start:Row的交叉轴是垂直方向,默认子组件会垂直居中,设置成start就能让容器贴紧Row的顶部,也就是你要的“左上/右上”效果。

方案2:用Spacer组件填充空白

如果需要更灵活的空间控制(比如后续要在中间加其他组件),可以用Spacer来自动填充两个容器之间的剩余空间,把蓝色容器挤到右侧:

class MyRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.red,
              ),
              // Spacer会自动占据Row内的剩余水平空间
              Spacer(),
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

两种方案都能达到你想要的效果,你可以根据实际需求选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:34:56