在Flutter中布局操作不当很容易就出现溢出的问题,也就是“A RenderFlex overflowed”错误。这里记录我自己出现的一个情况以及解决方法。
布局结构
我的布局结构是Container里面放个Cloumn,Column里面在垂直放Container和SingleChildScrollView。这时候就会出现布局溢出问题。因为我在Cloumn这种没有确定高度的Widget中用了一个没有确定高度的子Widget。
child: Container(
child: Column(
children: <Widget>[
Container(
width: itemWidth+50,
height: ScreenUtils.topSafeHeight,
),
SingleChildScrollView(
child: Column(
children: _renderList(context),
),
),
],
),
),
解决办法
使用Expanded,我们先看下Expanded的源码怎么说的,创建一个小部件,用于展开[Row],[Column]或[Flex]的子项
class Expanded extends Flexible {
/// Creates a widget that expands a child of a [Row], [Column], or [Flex]
/// so that the child fills the available space along the flex widget's
/// main axis.
const Expanded({
Key key,
int flex = 1,
@required Widget child,
}) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);
}
修改后的代码
child: Container(
child: Column(
children: <Widget>[
Container(
width: itemWidth+50,
height: ScreenUtils.topSafeHeight,
),
Expanded(
SingleChildScrollView(
child: Column(
children: _renderList(context),
),
),
),
],
),
),