Flutter

Flutter 之 流式布局 (四十一)

2022-04-30  本文已影响0人  maskerII

在使用Row 和 Colum 布局时,如果子 widget 超出屏幕范围,则会报溢出错误。如:

Row(
  children: <Widget>[
    Text("xxx"*100)
  ],
);

运行效果如下:

image.png

可以看到,右边溢出部分报错。这是因为Row默认只有一行,如果超出屏幕不会折行。

我们把超出屏幕显示范围会自动折行的布局称为流式布局。Flutter中通过WrapFlow来支持流式布局,将上例中的 Row 换成Wrap后溢出部分则会自动折行。

1. Wrap

Wrap的定义:

Wrap({
  ...
  this.direction = Axis.horizontal,
  this.alignment = WrapAlignment.start,
  this.spacing = 0.0,
  this.runAlignment = WrapAlignment.start,
  this.runSpacing = 0.0,
  this.crossAxisAlignment = WrapCrossAlignment.start,
  this.textDirection,
  this.verticalDirection = VerticalDirection.down,
  List<Widget> children = const <Widget>[],
})

Wrap的很多属性在Row(包括Flex和Column)中也有,如direction、crossAxisAlignment、textDirection、verticalDirection等,这些参数意义是相同的。

direction 主轴方向
alignment 对齐方式
verticalDirection:垂直方向子组件的布局顺序
crossAxisAlignment:子组件在纵轴方向的对齐方式
textDirection:水平方向子组件的布局顺序(是从左往右还是从右往左)

Wrap特有的几个属性

示例

class MSWrapDemo1 extends StatelessWidget {
  const MSWrapDemo1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Wrap(
          direction: Axis.horizontal,
          spacing: 8.0, // 主轴方向间距
          runSpacing: 4.0, // 纵轴方向间距
          alignment: WrapAlignment.center, // 沿主轴方向居中
          children: [
            Chip(
              avatar: CircleAvatar(
                  backgroundColor: Colors.blue[200], child: Text("A")),
              label: Text("Hamilton"),
            ),
            Chip(
              avatar: CircleAvatar(
                  backgroundColor: Colors.blue[200], child: Text("M")),
              label: Text("Lafayette"),
            ),
            Chip(
              avatar: CircleAvatar(
                  backgroundColor: Colors.blue[200], child: Text("H")),
              label: Text("Mulligan"),
            ),
            Chip(
              avatar: CircleAvatar(
                  backgroundColor: Colors.blue[200], child: Text("J")),
              label: Text("Laurens"),
            ),
            Chip(
              avatar: CircleAvatar(
                  backgroundColor: Colors.blue[200], child: Text("T")),
              label: Text("Tankey"),
            ),
          ],
        ),
      ),
    );
  }
}

image.png

2. Flow

一般很少会使用Flow,因为其过于复杂,需要自己实现子 widget 的位置转换,在很多场景下首先要考虑的是Wrap是否满足需求。Flow主要用于一些需要自定义布局策略或性能要求较高(如动画中)的场景。

Flow有如下优点:

缺点:

示例

对六个色块进行自定义流式布局

Flow(
  delegate: MSTestFlowDelegate(margin: EdgeInsets.all(12)),
  children: [
    Container(width: 80.0, height: 80.0, color: Colors.red),
    Container(width: 80.0, height: 80.0, color: Colors.blue),
    Container(width: 80.0, height: 80.0, color: Colors.green),
    Container(width: 80.0, height: 80.0, color: Colors.orange),
    Container(width: 80.0, height: 80.0, color: Colors.purple),
    Container(width: 80.0, height: 80.0, color: Colors.pink),
  ],
)

MSTestFlowDelegate


class MSTestFlowDelegate extends FlowDelegate {
  EdgeInsets margin;

  MSTestFlowDelegate({this.margin = EdgeInsets.zero});

  double width = 0;
  double height = 0;
  @override
  void paintChildren(FlowPaintingContext context) {
    var x = margin.left;
    var y = margin.top;

    //计算每一个子widget的位置
    for (var i = 0; i < context.childCount; i++) {
      var w = context.getChildSize(i)!.width + x + margin.right;
      if (w < context.size.width) {
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x = w + margin.left;
      } else {
        x = margin.left;
        y += context.getChildSize(i)!.height + margin.top + margin.bottom;

        //绘制子widget(有优化)
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x += context.getChildSize(i)!.width + margin.left + margin.right;
      }
    }
  }

  @override
  Size getSize(BoxConstraints constraints) {
    // 指定Flow的大小,简单起见我们让宽度竟可能大,但高度指定为200,
    // 实际开发中我们需要根据子元素所占用的具体宽高来设置Flow大小
    return Size(double.infinity, 200);
  }

  @override
  bool shouldRepaint(covariant FlowDelegate oldDelegate) {
    return oldDelegate != this;
  }
}

完整代码


class MSFlowDemo1 extends StatelessWidget {
  const MSFlowDemo1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Flow(
        delegate: MSTestFlowDelegate(margin: EdgeInsets.all(12)),
        children: [
          Container(width: 80.0, height: 80.0, color: Colors.red),
          Container(width: 80.0, height: 80.0, color: Colors.blue),
          Container(width: 80.0, height: 80.0, color: Colors.green),
          Container(width: 80.0, height: 80.0, color: Colors.orange),
          Container(width: 80.0, height: 80.0, color: Colors.purple),
          Container(width: 80.0, height: 80.0, color: Colors.pink),
        ],
      ),
    );
  }
}

class MSTestFlowDelegate extends FlowDelegate {
  EdgeInsets margin;

  MSTestFlowDelegate({this.margin = EdgeInsets.zero});

  double width = 0;
  double height = 0;
  @override
  void paintChildren(FlowPaintingContext context) {
    var x = margin.left;
    var y = margin.top;

    //计算每一个子widget的位置
    for (var i = 0; i < context.childCount; i++) {
      var w = context.getChildSize(i)!.width + x + margin.right;
      if (w < context.size.width) {
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x = w + margin.left;
      } else {
        x = margin.left;
        y += context.getChildSize(i)!.height + margin.top + margin.bottom;

        //绘制子widget(有优化)
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x += context.getChildSize(i)!.width + margin.left + margin.right;
      }
    }
  }

  @override
  Size getSize(BoxConstraints constraints) {
    // 指定Flow的大小,简单起见我们让宽度竟可能大,但高度指定为200,
    // 实际开发中我们需要根据子元素所占用的具体宽高来设置Flow大小
    return Size(double.infinity, 200);
  }

  @override
  bool shouldRepaint(covariant FlowDelegate oldDelegate) {
    return oldDelegate != this;
  }
}

image.png

可以看到我们主要的任务就是实现paintChildren,它的主要任务是确定每个子widget位置。由于Flow不能自适应子widget的大小,我们通过在getSize返回一个固定大小来指定Flow的大小。

注意,如果我们需要自定义布局策略,一般首选的方式是通过直接继承RenderObject,然后通过重写 performLayout 的方式实现。

https://book.flutterchina.club/chapter4/wrap_and_flow.html

上一篇 下一篇

猜你喜欢

热点阅读