弹性布局允许子组件按照一定比例来分配父容器空间。弹性布局的概念在其他UI系统中也都存在,如 H5 中的弹性盒子布局,Android中 的FlexboxLayout等。Flutter 中的弹性布局主要通过Flex和Expanded来配合实现。
4.1.Flex
Flex组件可以沿着水平或垂直方向排列子组件,如果你知道主轴方向,使用Row或Column会方便一些,因为Row和Column都继承自Flex,参数基本相同,所以能使用Flex的地方基本上都可以使用Row或Column。Flex本身功能是很强大的,它也可以和Expanded组件配合实现弹性布局。接下来我们只讨论Flex和弹性布局相关的属性(其他属性已经在介绍Row和Column时介绍过了)。

Flex相关参数
Flex继承自MultiChildRenderObjectWidget,对应的RenderObject为RenderFlex,RenderFlex中实现了其布局算法。
4.2 Expanded
Expanded 只能作为 Flex 的孩子(否则会报错),它可以按比例“扩伸”Flex子组件所占用的空间。因为 Row和Column 都继承自 Flex,所以 Expanded 也可以作为它们的孩子。我们先举一个简单的例子如下
Flex(
direction:Axis.horizontal ,
children: [
Text('测试Flex'),
Expanded(
child:Text('测试Expanded'*3)
)
],
)

Flex和Expanded配合使用的效果
我们在深入看看Expanded的相关参数

Expanded的相关参数
flex参数为弹性系数,如果为 0 或null,则child是没有弹性的,即不会被扩伸占用的空间。如果大于0,所有的Expanded按照其 flex 的比例来分割主轴的全部空闲空间。下面我们看一个例子:
下面我们再看一个完整的实例
Column(
children: [
Flex(
direction:Axis.horizontal ,//水平方向
children: [
Expanded(
flex:1,
child:Container(
height: 50,
color: Colors.cyanAccent,
child: const Center(
child: Text('占比是1'),
),
)
),
Expanded(
flex:2,
child:Container(
height: 50,
color: Colors.red,
child: const Center(
child: Text('占比是2'),
),
)
)
],
),
Padding(
padding: const EdgeInsets.only(top: 30),
child: SizedBox(
height: 100,
child: Flex(
direction: Axis.vertical,//竖直
children: [
Expanded(
flex: 2,
child: Container(
height: 30.0,
color: Colors.red,
),
),
Expanded(
flex: 2,
child: Container(
height: 30.0,
color: Colors.black,
),
),
Expanded(
flex: 1,
child: Container(
height: 30.0,
color: Colors.green,
),
),
],
),
)
)
],
)
最终效果

flex配合Expanded完整示例