Flutter 弹性布局

1,929 阅读1分钟

弹性布局简单来说就是允许子组件按照一定的比例来分配父容器的空间。

在flutter中我们使用flex和expanded实现弹性布局。其中Row和Column布局都是继承自Flex,如果你能够明确主轴方向,那么使用Row和Column布局更为方便。Flex布局同样可以实现水平和垂直方向的控件布局。

关于Flex的可用属性可参考源代码:

在这里我们主要关心一个新的属性direction,其可选值如下:

Expanded组件

该组件可以按比例来扩伸Row、Column和Flex组件所占用的空间。

这里我们需要通过其flex属性来指定组件的弹性系数。如果为0或null,则child是没有弹性的,即不会被扩伸占用的空间。如果大于0,所有的Expanded按照其flex的比例来分割主轴的全部空闲空间。

import 'package:flutter/material.dart';

class FlexLayout extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                height: 30,
                color: Colors.red,
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: 30,
                color: Colors.amber,
              ),
            )
          ],
        ),
        Padding(
          padding: const EdgeInsets.only(top: 20),
          child: Container(
            height: 100,
            color: Colors.yellow,
            child: Flex(
              direction: Axis.vertical,
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Container(
                    height: 30,
                    color: Colors.black,
                  ),

                ),
                Spacer(
                  flex: 1,
                ),
                Expanded(
                  flex: 2,
                  child: Container(
                    height: 30,
                    color: Colors.green,
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

}

此时程序效果如下:

注意在垂直布局中使用弹性布局时,请务必要指定父容器的高度,不然后得到如下错误:

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
The following assertion was thrown during performLayout():
RenderFlex children have non-zero flex but incoming height constraints are unbounded.

Expanded组件会自动填充可用空间,比如:

Row(
          children: <Widget>[
            Text(
            'hello flutter'
            ),
            Expanded(
              child: Container(
                height: 30,
                color: Colors.red,
              ),
            )
          ],
        )