Flutter Sliver你要的瀑布流小姐姐

image

前言

今天看了Flutter Interact, 全程有個(gè)小姐姐翻譯(同聲翻譯,好強(qiáng)力),于是我就邊聽邊完成了這篇文章。


image

接著上一章Flutter Sliver一生之?dāng)?(ExtendedList),這章我們將編寫一個(gè)瀑布流布局,來檢驗(yàn)一下我們上一章對Sliver列表源碼分析是否正確。

歡迎加入Flutter Candies <a target="_blank" ><img border="0" src="https://user-gold-cdn.xitu.io/2019/10/27/16e0ca3f1a736f0e?w=90&h=22&f=png&s=1827" alt="flutter-candies" title="flutter-candies"></a> QQ群: 181398081。

image

知道你們只關(guān)心小姐姐,我還是先放效果圖吧。

image
image
image
image

原理

之前做UWP的時(shí)候,我自己也做過瀑布流布局。似乎是一種執(zhí)念,入坑Flutter之后也想實(shí)現(xiàn)一下瀑布流布局。下面簡單講一下什么是瀑布流以及原理。

瀑布流布局的特點(diǎn)是等寬不等高。
為了讓最后一行的差距最小,從第二行開始,需要將一項(xiàng)放在第一行最矮的一項(xiàng)下面,以此類推,如下圖。4在0下面,5在3下面,6在1下面,7在2下面,8在4下面...

image

核心代碼

知道了原理,下面我們來一起把原理實(shí)現(xiàn)為代碼。

  • 由于我們需要知道離viewport頂部最近的Items,以及viewport底部最近的Items。這樣才能知道向后滾動(dòng)新的item放哪個(gè)item下面,或者說向前滾動(dòng)的時(shí)候知道新的item放在哪個(gè)item的上面
    我設(shè)計(jì)了CrossAxisItems 來存放leadingItems 和 trailingItems。

  • 向后添加新的item的時(shí)候代碼如下

1.補(bǔ)充leadingItems直到等于crossAxisCount

2.找到當(dāng)前最矮的一項(xiàng),將設(shè)置它的layoutoffset

3.保存這一列的indexes

  void insert({
    @required RenderBox child,
    @required ChildTrailingLayoutOffset childTrailingLayoutOffset,
    @required PaintExtentOf paintExtentOf,
  }) {
    final WaterfallFlowParentData data = child.parentData;
    final LastChildLayoutType lastChildLayoutType =
        delegate.getLastChildLayoutType(data.index);
    
    ///處理最后一個(gè)特殊化布局
    switch (lastChildLayoutType) {
      case LastChildLayoutType.fullCrossAxisExtend:
      case LastChildLayoutType.foot:
        //橫軸繪制offset
        data.crossAxisOffset = 0.0;
        //橫軸index
        data.crossAxisIndex = 0;
        //該child的大小
        final size = paintExtentOf(child);
        
        if (lastChildLayoutType == LastChildLayoutType.fullCrossAxisExtend ||
            maxChildTrailingLayoutOffset + size >
                constraints.remainingPaintExtent) {
          data.layoutOffset = maxChildTrailingLayoutOffset;
        } else {
          //如果全部children沒有繪制viewport的大
          data.layoutOffset = constraints.remainingPaintExtent - size;
        }
        data.trailingLayoutOffset = childTrailingLayoutOffset(child);
        return;
      case LastChildLayoutType.none:
        break;
    }

    if (!leadingItems.contains(data)) {
      //補(bǔ)充滿leadingItems
      if (leadingItems.length != crossAxisCount) {
        data.crossAxisIndex ??= leadingItems.length;

        data.crossAxisOffset =
            delegate.getCrossAxisOffset(constraints, data.crossAxisIndex);

        if (data.index < crossAxisCount) {
          data.layoutOffset = 0.0;
          data.indexs.clear();
        }

        trailingItems.add(data);
        leadingItems.add(data);
      } else {
        if (data.crossAxisIndex != null) {
          var item = trailingItems.firstWhere(
              (x) =>
                  x.index > data.index &&
                  x.crossAxisIndex == data.crossAxisIndex,
              orElse: () => null);

          ///out of viewport
          if (item != null) {
            data.trailingLayoutOffset = childTrailingLayoutOffset(child);
            return;
          }
        }
        //找到最矮的那個(gè)
        var min = trailingItems.reduce((curr, next) =>
            ((curr.trailingLayoutOffset < next.trailingLayoutOffset) ||
                    (curr.trailingLayoutOffset == next.trailingLayoutOffset &&
                        curr.crossAxisIndex < next.crossAxisIndex)
                ? curr
                : next));

        data.layoutOffset = min.trailingLayoutOffset + delegate.mainAxisSpacing;
        data.crossAxisIndex = min.crossAxisIndex;
        data.crossAxisOffset =
            delegate.getCrossAxisOffset(constraints, data.crossAxisIndex);

        trailingItems.forEach((f) => f.indexs.remove(min.index));
        min.indexs.add(min.index);
        data.indexs = min.indexs;
        trailingItems.remove(min);
        trailingItems.add(data);
      }
    }

    data.trailingLayoutOffset = childTrailingLayoutOffset(child);
  }
  • 向前添加新的item的時(shí)候代碼如下

1.通過indexs找到新item屬于哪一列

2.添加到舊的item的上面

  void insertLeading({
    @required RenderBox child,
    @required PaintExtentOf paintExtentOf,
  }) {
    final WaterfallFlowParentData data = child.parentData;
    if (!leadingItems.contains(data)) {
      var pre = leadingItems.firstWhere((x) => x.indexs.contains(data.index),
          orElse: () => null);

      if (pre == null || pre.index < data.index) return;

      data.trailingLayoutOffset = pre.layoutOffset - delegate.mainAxisSpacing;
      data.crossAxisIndex = pre.crossAxisIndex;
      data.crossAxisOffset =
          delegate.getCrossAxisOffset(constraints, data.crossAxisIndex);

      leadingItems.remove(pre);
      leadingItems.add(data);
      trailingItems.remove(pre);
      trailingItems.add(data);
      data.indexs = pre.indexs;

      data.layoutOffset = data.trailingLayoutOffset - paintExtentOf(child);
    }
  }
  • 計(jì)算離viewport頂部最近的,應(yīng)該確保leadingItems都在viewport里面
    跟之前Listview的源碼分析差不多,只是這里我們要保證最大的LeadingLayoutOffset都小于scrollOffset,這樣leadingItems就都在viewport里面了
    if (crossAxisItems.maxLeadingLayoutOffset > scrollOffset) {
      RenderBox child = firstChild;
      //move to max index of leading
      final int maxLeadingIndex = crossAxisItems.maxLeadingIndex;
      while (child != null && maxLeadingIndex > indexOf(child)) {
        child = childAfter(child);
      }
      //fill leadings from max index of leading to min index of leading
      while (child != null && crossAxisItems.minLeadingIndex < indexOf(child)) {
        crossAxisItems.insertLeading(
            child: child, paintExtentOf: paintExtentOf);
        child = childBefore(child);
      }
      //collectGarbage(maxLeadingIndex - index, 0);

      while (crossAxisItems.maxLeadingLayoutOffset > scrollOffset) {
        // We have to add children before the earliestUsefulChild.
        earliestUsefulChild =
            insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true);

        if (earliestUsefulChild == null) {
          if (scrollOffset == 0.0) {
            // insertAndLayoutLeadingChild only lays out the children before
            // firstChild. In this case, nothing has been laid out. We have
            // to lay out firstChild manually.
            firstChild.layout(childConstraints, parentUsesSize: true);

            earliestUsefulChild = firstChild;
            leadingChildWithLayout = earliestUsefulChild;
            trailingChildWithLayout ??= earliestUsefulChild;
            crossAxisItems.reset();
            crossAxisItems.insert(
              child: earliestUsefulChild,
              childTrailingLayoutOffset: childTrailingLayoutOffset,
              paintExtentOf: paintExtentOf,
            );
            break;
          } else {
            // We ran out of children before reaching the scroll offset.
            // We must inform our parent that this sliver cannot fulfill
            // its contract and that we need a scroll offset correction.
            geometry = SliverGeometry(
              scrollOffsetCorrection: -scrollOffset,
            );
            return;
          }
        }

        crossAxisItems.insertLeading(
            child: earliestUsefulChild, paintExtentOf: paintExtentOf);

        final WaterfallFlowParentData data = earliestUsefulChild.parentData;

        // firstChildScrollOffset may contain double precision error
        if (data.layoutOffset < -precisionErrorTolerance) {
          // The first child doesn't fit within the viewport (underflow) and
          // there may be additional children above it. Find the real first child
          // and then correct the scroll position so that there's room for all and
          // so that the trailing edge of the original firstChild appears where it
          // was before the scroll offset correction.
          // do this work incrementally, instead of all at once,
          // i.e. find a way to avoid visiting ALL of the children whose offset
          // is < 0 before returning for the scroll correction.
          double correction = 0.0;
          while (earliestUsefulChild != null) {
            assert(firstChild == earliestUsefulChild);
            correction += paintExtentOf(firstChild);
            earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints,
                parentUsesSize: true);
            crossAxisItems.insertLeading(
                child: earliestUsefulChild, paintExtentOf: paintExtentOf);
          }
          geometry = SliverGeometry(
            scrollOffsetCorrection: correction - data.layoutOffset,
          );
          return;
        }

        assert(earliestUsefulChild == firstChild);
        leadingChildWithLayout = earliestUsefulChild;
        trailingChildWithLayout ??= earliestUsefulChild;
      }
    }
  • 計(jì)算達(dá)到viewport底部,應(yīng)該確保trailingItems中最短的要超過viewport的底部
    // Now find the first child that ends after our end.
    if (child != null) {
      while (crossAxisItems.minChildTrailingLayoutOffset <
              targetEndScrollOffset ||
              //make sure leading children are painted. 
          crossAxisItems.leadingItems.length < _gridDelegate.crossAxisCount
          || crossAxisItems.leadingItems.length  > childCount
          ) {
        if (!advance()) {
          reachedEnd = true;
          break;
        }
      }
    }

waterfall_flow使用

  • 在pubspec.yaml中增加庫引用

dependencies:
  waterfall_flow: any

  • 導(dǎo)入庫

  import 'package:waterfall_flow/waterfall_flow.dart';
  

如何定義

你可以通過設(shè)置SliverWaterfallFlowDelegate參數(shù)來定義瀑布流

參數(shù) 描述 默認(rèn)
crossAxisCount 橫軸的等長度元素?cái)?shù)量 必填
mainAxisSpacing 主軸元素之間的距離 0.0
crossAxisSpacing 橫軸元素之間的距離 0.0
collectGarbage 元素回收時(shí)候的回調(diào) -
lastChildLayoutTypeBuilder 最后一個(gè)元素的布局樣式(詳情請查看后面) -
viewportBuilder 可視區(qū)域中元素indexes變化時(shí)的回調(diào) -
closeToTrailing 可否讓布局緊貼trailing(詳情請查看后面) false
            WaterfallFlow.builder(
              //cacheExtent: 0.0,
              padding: EdgeInsets.all(5.0),
              gridDelegate: SliverWaterfallFlowDelegate(
                  crossAxisCount: 2,
                  crossAxisSpacing: 5.0,
                  mainAxisSpacing: 5.0,
                  /// follow max child trailing layout offset and layout with full cross axis extend
                  /// last child as loadmore item/no more item in [GridView] and [WaterfallFlow]
                  /// with full cross axis extend
                  //  LastChildLayoutType.fullCrossAxisExtend,

                  /// as foot at trailing and layout with full cross axis extend
                  /// show no more item at trailing when children are not full of viewport
                  /// if children is full of viewport, it's the same as fullCrossAxisExtend
                  //  LastChildLayoutType.foot,
                  lastChildLayoutTypeBuilder: (index) => index == _list.length
                      ? LastChildLayoutType.foot
                      : LastChildLayoutType.none,
                  ),

完整小姐姐Demo

結(jié)語

沒有再對源碼有更多的分析,上一篇如果你看過了,應(yīng)該會(huì)更加明白其中的道理。這一篇是對瀑布流原理在Flutter上面實(shí)現(xiàn)的展示,沒有做不到效果,只有想不到的效果,這就是Flutter給我?guī)淼捏w驗(yàn)。

最后放上Flutter Interact 的一些內(nèi)容,我是邊聽邊寫的,如果有誤,請?zhí)嵝盐腋南隆?/p>

  • Flutter 1.12版本
  • Material design 以及字體庫
  • 帶來了Desktop/Web(你現(xiàn)在可以嘗試他們了,不再是玩具)
  • 叼炸天的各種開發(fā)工具(同時(shí)調(diào)試7種設(shè)備,UI化界面)
  • gskinner 酷炫交互+開源
  • supernova 知名的 design-to-code (設(shè)計(jì)轉(zhuǎn)代碼) 工具
  • Adobe XD 程序猿們顫抖吧,UI將代替你們了。
  • flutter_vignettes商業(yè)互吹
  • rive.app展示了一個(gè)炒雞可愛的游戲,而且是用Flutter web

歡迎加入Flutter Candies,一起生產(chǎn)可愛的Flutter小糖果( <a target="_blank" ><img border="0" src="https://user-gold-cdn.xitu.io/2019/10/27/16e0ca3f1a736f0e?w=90&h=22&f=png&s=1827" alt="flutter-candies" title="flutter-candies"></a>QQ群:181398081)

最最后放上Flutter Candies全家桶,真香。

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容