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

如何在Flutter中使用Container类将屏幕均分为3等份?

Flutter 用Container实现屏幕三等分的方案

实现屏幕三等分有两种常用方案,分别适配不同的使用场景:

方案1:Expanded + Column/Row (推荐,适配性最优)

这是最常用的实现方式,不需要手动计算尺寸,横竖屏切换、不同尺寸设备都能自动适配。
如果要做垂直三等分(上下三块),直接套Column加三个Expanded包裹Container即可:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: const [
            Expanded(
              child: Container(
                color: Colors.red,
                // 这里可以加Container的其他属性:padding、child、decoration等
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.green,
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.blue,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

如果要做水平三等分(左右三块),只需要把外层的Column换成Row即可,其他代码完全不变。
原理:Expanded默认flex权重为1,三个权重相同的Expanded会自动平分父容器的全部可用空间,内部的Container会自动撑满Expanded的尺寸。

方案2:MediaQuery 手动计算尺寸(适合固定尺寸场景)

如果你需要明确拿到每块的尺寸做其他逻辑,可以用MediaQuery先获取屏幕的尺寸,再给Container设置固定高/宽:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 垂直三等分的话取屏幕高度,水平的话取宽度
    final screenHeight = MediaQuery.of(context).size.height;
    // 注意:如果页面有AppBar、状态栏,要扣除对应的高度,比如:
    // final availableHeight = screenHeight - MediaQuery.of(context).padding.top - kToolbarHeight;
    final eachHeight = screenHeight / 3;

    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            Container(
              height: eachHeight,
              color: Colors.red,
            ),
            Container(
              height: eachHeight,
              color: Colors.green,
            ),
            Container(
              height: eachHeight,
              color: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  • 优先选方案1,不需要手动处理适配问题,也不会出现布局溢出
  • 如果需要给三块之间加间距,直接给Container加margin属性即可,不要修改Expanded的外层布局避免破坏均分效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:27:01