Flutter实现四个Container垂直排列 解决红色Container覆盖其他组件问题
问题解决
问题根源
- 你没有给四个Container外层包裹垂直布局组件
Column,无垂直布局约束时Container会按堆叠逻辑展示,自然会出现覆盖情况 - 第一个Container设置了满屏高度
MediaQuery.of(context).size.height,就算加上了Column布局,四个Container总高度也会远超屏幕尺寸,出现溢出或展示异常
解决方案
方案1:手动计算高度适配满屏
如果要刚好铺满一整屏,四个Container的高度总和需要等于屏幕高度,你可以按需求比例分配,比如前三个按1/2、1/4、1/8的比例,最后一个红色Container设置为1/8即可,修改后代码如下:
// 外层必须套Column,实现垂直排列逻辑 Column( children: [ Container( color: BColors.tealBackground, height: MediaQuery.of(context).size.height / 2, ), Container( color: BColors.greenBackground, height: MediaQuery.of(context).size.height / 4, ), Container( color: BColors.yellowBackground, height: MediaQuery.of(context).size.height / 8, ), Container( color: BColors.redBackground, height: MediaQuery.of(context).size.height / 8, ), ], )
这里四个高度加起来刚好等于屏幕总高度,不会出现溢出或覆盖问题。
方案2:弹性布局自动分配(更推荐)
不需要手动计算媒体查询高度,用Expanded的flex属性自动分配垂直空间,适配所有屏幕尺寸,不会出现计算错误:
Column( children: [ Expanded( flex: 4, // 占4份空间 child: Container(color: BColors.tealBackground), ), Expanded( flex: 2, // 占2份空间 child: Container(color: BColors.greenBackground), ), Expanded( flex: 1, // 占1份空间 child: Container(color: BColors.yellowBackground), ), Expanded( flex: 1, // 占1份空间 child: Container(color: BColors.redBackground), ), ], )
你可以自行调整flex的数值来修改各个Container的高度占比,总flex数是多少,每个Container的占比就是自身flex值除以总flex值。
超出一屏可滚动的场景
如果不需要铺满一屏,内容超过屏幕高度时需要滚动,外层套SingleChildScrollView即可,这时候可以给Container设置任意固定高度:
SingleChildScrollView( child: Column( children: [ // 四个自定义高度的Container ], ), )
内容的提问来源于stack exchange,提问作者Alpaka404
相关产品推荐
相关产品推荐

