Flutter Sliver一生之敵 (ScrollView)

法的空間發表於2019-12-01

Flutter Sliver一生之敵 (ScrollView)

前言

入坑Flutter一年了,接觸到Flutter也只是冰山一角,很多東西可能知道是怎麼用的,但是不是很明白其中的原理,俗話說唯有深入,方能淺出。本系列將對Sliver相關原始碼一一進行分析,希望能夠舉一反三,不再懼怕Sliver。

Flutter Sliver一生之敵 (ScrollView)
Flutter Sliver一生之敵 今年將有4章,一章比一章勁爆,你將不會害怕使用Sliver,Sliver將成為你的一生之愛。歡迎加入Flutter Candies flutter-candies QQ群: 181398081。

下面是全部滾動的元件,以及他們的關係

Widget Build Viewport
SingleChildScrollView Scrollable _SingleChildViewport
ScrollView Scrollable ShrinkWrappingViewport/Viewport

Sliver系列繼承於ScrollView

Widget Extends
CustomScrollView ScrollView
NestedScrollView CustomScrollView
ListView/GridView BoxScrollView => ScrollView

簡單講滾動元件由Scrollable獲取使用者手勢反饋,將滾動反饋和Slivers傳遞給Viewport計算出Sliver的位置。注意Sliver可以是單孩子(SliverPadding/SliverPersistentHeader/SliverToBoxAdapter等等)也可以是多孩子(SliverList/SliverGrid)。下面我們通過分析原始碼,探究其中奧祕。

ScrollView

下面為build方法中的關鍵程式碼,這裡是我們上面說的Scrollable,主要負責使用者手勢監聽反饋。

    final Scrollable scrollable = Scrollable(
      dragStartBehavior: dragStartBehavior,
      axisDirection: axisDirection,
      controller: scrollController,
      physics: physics,
      semanticChildCount: semanticChildCount,
      viewportBuilder: (BuildContext context, ViewportOffset offset) {
        return buildViewport(context, offset, axisDirection, slivers);
      },
    );
複製程式碼

我們再看看buildViewport方法

  @protected
  Widget buildViewport(
    BuildContext context,
    ViewportOffset offset,
    AxisDirection axisDirection,
    List<Widget> slivers,
  ) {
    if (shrinkWrap) {
      return ShrinkWrappingViewport(
        axisDirection: axisDirection,
        offset: offset,
        slivers: slivers,
      );
    }
    return Viewport(
      axisDirection: axisDirection,
      offset: offset,
      slivers: slivers,
      cacheExtent: cacheExtent,
      center: center,
      anchor: anchor,
    );
  }
複製程式碼

根據shrinkWrap的不同,分成了2種Viewport

Scrollable

用於監聽各種使用者手勢並實現滾動,下面為build方法中的關鍵程式碼。

    //InheritedWidget元件,為了共享position資料
    Widget result = _ScrollableScope(
      scrollable: this,
      position: position,
      // TODO(ianh): Having all these global keys is sad.
      child: Listener(
        onPointerSignal: _receivedPointerSignal,
        child: RawGestureDetector(
          key: _gestureDetectorKey,
          gestures: _gestureRecognizers,
          behavior: HitTestBehavior.opaque,
          excludeFromSemantics: widget.excludeFromSemantics,
          child: Semantics(
            explicitChildNodes: !widget.excludeFromSemantics,
            child: IgnorePointer(
              key: _ignorePointerKey,
              ignoring: _shouldIgnorePointer,
              ignoringSemantics: false,
              //通過Listener監聽手勢,將滾動position通過viewportBuilder回撥。
              child: widget.viewportBuilder(context, position),
            ),
          ),
        ),
      ),
    );
    
   //這裡可以看到為什麼安卓和ios上面對於滾動越界(overscrolls)時候的操作不一樣    
   return _configuration.buildViewportChrome(context, result, widget.axisDirection);
複製程式碼

安卓和fuchsia上面使用GlowingOverscrollIndicator來顯示滾動不了之後的水波紋效果。

  /// Wraps the given widget, which scrolls in the given [AxisDirection].
  ///
  /// For example, on Android, this method wraps the given widget with a
  /// [GlowingOverscrollIndicator] to provide visual feedback when the user
  /// overscrolls.
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) {
    // When modifying this function, consider modifying the implementation in
    // _MaterialScrollBehavior as well.
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
        return child;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        return GlowingOverscrollIndicator(
          child: child,
          axisDirection: axisDirection,
          color: _kDefaultGlowColor,
        );
    }
    return null;
  }
複製程式碼

Viewport

通過只顯示(計算繪製)滾動檢視中的一部分內容來實現滾動視覺化設計,大大降低記憶體消耗。比如ListView可視區域為666畫素,但其列表元素的總高度遠遠超過666畫素,但實際上我們只是關心這個666畫素中的元素(當然如果設定了CacheExtent,還要算上這個距離)

在Scrollview中將Scrollable滾動反饋以及Slivers傳遞給了Viewport。Viewport 是一個MultiChildRenderObjectWidget,lei了lei了,這是一個自繪多孩子的元件。直接找到createRenderObject方法,看到返回一個RenderViewport

RenderViewport

重頭戲來了,我們看看構造引數有哪些。

  RenderViewport({
    //主軸方向,預設向下
    AxisDirection axisDirection = AxisDirection.down,
    //縱軸方向,跟主軸方向以及有關係
    @required AxisDirection crossAxisDirection,
    //Scrollable中回撥的使用者反饋
    @required ViewportOffset offset,
    //當scrollOffset = 0,第一個child在viewport的位置(0 <= anchor <= 1.0),0.0在leading,1.0在trailing,0.5在中間
    double anchor = 0.0,
    //sliver孩子們
    List<RenderSliver> children,
    //The first child in the [GrowthDirection.forward] growth direction.
    //計算時候的基準,預設為第一個娃,這個引數估計極少有人使用
    RenderSliver center,
    //快取區域大小
    double cacheExtent,
    //決定cacheExtent是實際大小還是根據viewport的百分比
    CacheExtentStyle cacheExtentStyle = CacheExtentStyle.pixel,
  })... {
    addAll(children);
    if (center == null && firstChild != null)
      _center = firstChild;
  }
複製程式碼

可以看到構造中把全部孩子都加進入了,而且如果外部不傳遞center,center預設為第一個孩子。

劃重點程式碼分析

sizedByParent

在Viewport中這個值永遠返回true,

  @override
  bool get sizedByParent => true;
複製程式碼

來看看這個屬性的解釋。即如果這個值為true,那麼元件的大小隻跟它的parent告訴它的大小constraints有關係,與它的 child 都無關.

就是說RenderViewport的大小約束是由它的parent告訴它的,跟裡面的Slivers沒有關係。說到這個我們看一個新手經常錯誤的程式碼。

     Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '測試',
            ),
            ListView.builder(itemBuilder: (context,index){})
          ],
        ),
複製程式碼

我們前面知道ListView最終是一個ScrollView,其中的Viewport在Column當中是無法知道自己的有效大小的,該程式碼的會導致Viewport的高度為無限大,將會報錯(當然你這裡可以把shrinkWrap設定為true,但是這樣會導致ListView的全部元素都被計算,列表將失去滾動,這個我們後面會講)

繼續看程式碼中看到,當sizedByParent為true的時候呼叫performResize方法,指定Size只根據constraints。

    if (sizedByParent) {
      assert(() {
        _debugDoingThisResize = true;
        return true;
      }());
      try {
        performResize();
        assert(() {
          debugAssertDoesMeetConstraints();
          return true;
        }());
      } catch (e, stack) {
        _debugReportException('performResize', e, stack);
      }
      assert(() {
        _debugDoingThisResize = false;
        return true;
      }());
    }
複製程式碼

performResize

看看RenderViewport的performResize中做了什麼。有一大堆assert,就一句話,我不能無限大。最後將自己的size設定為constraints.biggest。 (size是自己的大小,constraints是parent給的限制)

  @override
  void performResize() {
    assert(() {
      if (!constraints.hasBoundedHeight || !constraints.hasBoundedWidth) {
        switch (axis) {
          case Axis.vertical:
            if (!constraints.hasBoundedHeight) {
              throw FlutterError.fromParts(<DiagnosticsNode>[
                ErrorSummary('Vertical viewport was given unbounded height.'),
                ErrorDescription(
                  'Viewports expand in the scrolling direction to fill their container. '
                  'In this case, a vertical viewport was given an unlimited amount of '
                  'vertical space in which to expand. This situation typically happens '
                  'when a scrollable widget is nested inside another scrollable widget.'
                ),
                ErrorHint(
                  'If this widget is always nested in a scrollable widget there '
                  'is no need to use a viewport because there will always be enough '
                  'vertical space for the children. In this case, consider using a '
                  'Column instead. Otherwise, consider using the "shrinkWrap" property '
                  '(or a ShrinkWrappingViewport) to size the height of the viewport '
                  'to the sum of the heights of its children.'
                )
              ]);
            }
            if (!constraints.hasBoundedWidth) {
              throw FlutterError(
                'Vertical viewport was given unbounded width.\n'
                'Viewports expand in the cross axis to fill their container and '
                'constrain their children to match their extent in the cross axis. '
                'In this case, a vertical viewport was given an unlimited amount of '
                'horizontal space in which to expand.'
              );
            }
            break;
          case Axis.horizontal:
            if (!constraints.hasBoundedWidth) {
              throw FlutterError.fromParts(<DiagnosticsNode>[
                ErrorSummary('Horizontal viewport was given unbounded width.'),
                ErrorDescription(
                  'Viewports expand in the scrolling direction to fill their container.'
                  'In this case, a horizontal viewport was given an unlimited amount of '
                  'horizontal space in which to expand. This situation typically happens '
                  'when a scrollable widget is nested inside another scrollable widget.'
                ),
                ErrorHint(
                  'If this widget is always nested in a scrollable widget there '
                  'is no need to use a viewport because there will always be enough '
                  'horizontal space for the children. In this case, consider using a '
                  'Row instead. Otherwise, consider using the "shrinkWrap" property '
                  '(or a ShrinkWrappingViewport) to size the width of the viewport '
                  'to the sum of the widths of its children.'
                )
              ]);
            }
            if (!constraints.hasBoundedHeight) {
              throw FlutterError(
                'Horizontal viewport was given unbounded height.\n'
                'Viewports expand in the cross axis to fill their container and '
                'constrain their children to match their extent in the cross axis. '
                'In this case, a horizontal viewport was given an unlimited amount of '
                'vertical space in which to expand.'
              );
            }
            break;
        }
      }
      return true;
    }());
    size = constraints.biggest;
    // We ignore the return value of applyViewportDimension below because we are
    // going to go through performLayout next regardless.
    switch (axis) {
      case Axis.vertical:
        offset.applyViewportDimension(size.height);
        break;
      case Axis.horizontal:
        offset.applyViewportDimension(size.width);
        break;
    }
  }
複製程式碼

performLayout

負責佈局RenderViewport的Children

    //從size中得到主軸和縱軸的大小
    double mainAxisExtent;
    double crossAxisExtent;
    switch (axis) {
      case Axis.vertical:
        mainAxisExtent = size.height;
        crossAxisExtent = size.width;
        break;
      case Axis.horizontal:
        mainAxisExtent = size.width;
        crossAxisExtent = size.height;
        break;
    }

    //如果單Sliver孩子的viewport高度為100,anchor為0.5,centerOffsetAdjustment設定為50.0的話,當scroll offset is 0.0的時候,center會剛好在viewport中間。
    final double centerOffsetAdjustment = center.centerOffsetAdjustment;

    double correction;
    int count = 0;
    do {
      assert(offset.pixels != null);
      correction = _attemptLayout(mainAxisExtent, crossAxisExtent, offset.pixels + centerOffsetAdjustment);
      ///如果不為0.0的話,是因為child中有需要修正(這個我們將在後面系列中講到,這裡我們就簡單認為在layout child過程中出現了問題),我們需要改變scroll offset之後重新layout chilren。
      if (correction != 0.0) {
        offset.correctBy(correction);
      } else {
        ///告訴Scrollable 最小滾動距離和最大滾動距離
        if (offset.applyContentDimensions(
              math.min(0.0, _minScrollExtent + mainAxisExtent * anchor),
              math.max(0.0, _maxScrollExtent - mainAxisExtent * (1.0 - anchor)),
           ))
          break;
      }
      count += 1;
    } while (count < _maxLayoutCycles);
複製程式碼

如果超過最大次數,children還是layout還是有問題的話,將警告提示。

下面我們看看_attemptLayout方法中做了什麼。

  double _attemptLayout(double mainAxisExtent, double crossAxisExtent, double correctedOffset) {
    assert(!mainAxisExtent.isNaN);
    assert(mainAxisExtent >= 0.0);
    assert(crossAxisExtent.isFinite);
    assert(crossAxisExtent >= 0.0);
    assert(correctedOffset.isFinite);
    _minScrollExtent = 0.0;
    _maxScrollExtent = 0.0;
    _hasVisualOverflow = false;

    //centerOffset的數值將使用anchor和offset.pixels + centerOffsetAdjustment進行修正。前面有講
    final double centerOffset = mainAxisExtent * anchor - correctedOffset;
    //反向RemainingPaintExtent,就是center之前還有多少距離可以拿來繪製
    final double reverseDirectionRemainingPaintExtent = centerOffset.clamp(0.0, mainAxisExtent);
    //正向RemainingPaintExtent,就是center之後還有多少距離可以拿來繪製
    final double forwardDirectionRemainingPaintExtent = (mainAxisExtent - centerOffset).clamp(0.0, mainAxisExtent);

    switch (cacheExtentStyle) {
      case CacheExtentStyle.pixel:
        _calculatedCacheExtent = cacheExtent;
        break;
      case CacheExtentStyle.viewport:
        _calculatedCacheExtent = mainAxisExtent * cacheExtent;
        break;
    }
    ///總的計算區域包含前後2個cacheExtent
    final double fullCacheExtent = mainAxisExtent + 2 * _calculatedCacheExtent;
    ///加上cacheExtent的center位置,跟前面的比就是多了cache
    final double centerCacheOffset = centerOffset + _calculatedCacheExtent;
     //反向RemainingPaintExtent,就是center之前還有多少距離可以拿來繪製,跟前面的比就是多了cache
    final double reverseDirectionRemainingCacheExtent = centerCacheOffset.clamp(0.0, fullCacheExtent);
     //正向RemainingPaintExtent,就是center之後還有多少距離可以拿來繪製,跟前面的比就是多了cache
    final double forwardDirectionRemainingCacheExtent = (fullCacheExtent - centerCacheOffset).clamp(0.0, fullCacheExtent);

    final RenderSliver leadingNegativeChild = childBefore(center);
    ///如果在center之前還有child,將向前layout child,計算前面佈局前面的child
    if (leadingNegativeChild != null) {
      // negative scroll offsets
      final double result = layoutChildSequence(
        child: leadingNegativeChild,
        scrollOffset: math.max(mainAxisExtent, centerOffset) - mainAxisExtent,
        overlap: 0.0,
        layoutOffset: forwardDirectionRemainingPaintExtent,
        remainingPaintExtent: reverseDirectionRemainingPaintExtent,
        mainAxisExtent: mainAxisExtent,
        crossAxisExtent: crossAxisExtent,
        growthDirection: GrowthDirection.reverse,
        advance: childBefore,
        remainingCacheExtent: reverseDirectionRemainingCacheExtent,
        cacheOrigin: (mainAxisExtent - centerOffset).clamp(-_calculatedCacheExtent, 0.0),
      );
      if (result != 0.0)
        return -result;
    }

    ///佈局center後面的child
    // positive scroll offsets
    return layoutChildSequence(
      child: center,
      scrollOffset: math.max(0.0, -centerOffset),
      overlap: leadingNegativeChild == null ? math.min(0.0, -centerOffset) : 0.0,
      layoutOffset: centerOffset >= mainAxisExtent ? centerOffset: reverseDirectionRemainingPaintExtent,
      remainingPaintExtent: forwardDirectionRemainingPaintExtent,
      mainAxisExtent: mainAxisExtent,
      crossAxisExtent: crossAxisExtent,
      growthDirection: GrowthDirection.forward,
      advance: childAfter,
      remainingCacheExtent: forwardDirectionRemainingCacheExtent,
      cacheOrigin: centerOffset.clamp(-_calculatedCacheExtent, 0.0),
    );
  }
複製程式碼

注意scrollOffset ,在向前和向後layout的時候不一樣, 一個是 math.max(mainAxisExtent, centerOffset) - mainAxisExtent 一個是 math.max(0.0, -centerOffset) 我們有說過center其實是scrolloffset為0的基準,viewport裡面如果有多個slivers,我們可以指定其中一個為center(預設第一個為center),那麼想前滾centerOffset會變大,想後滾centerOffset會變成負數。感覺還是有點抽象,下面給一個栗子,我給第2個sliver增加了key,並且把CustomScrollView的center賦值為這個key。小聲逼逼,Center這個引數我估計百分之99的人沒有用過,用過的請留言,我看看有多少人知道這個。

CustomScrollView(
        center: key,
        slivers: <Widget>[
        SliverList(),
        SliverGrid(key:key),
複製程式碼

執行起來初始centerOffset為0的時候SliverGrid在初始位置。

Flutter Sliver一生之敵 (ScrollView)
向前滾動,可以看到我們得到了逆向的SliverList,從我們的引數中也可以驗證到。而offset.pixels(ScollView的滾動位置)當然也為0.(而不是你們想的SliverList的高度)
Flutter Sliver一生之敵 (ScrollView)

再看下layoutChildSequence方法,注意到advance方法,向前其實呼叫的是childBefore,向後是呼叫的childAfter

  double layoutChildSequence({
    @required RenderSliver child,
    @required double scrollOffset,
    @required double overlap,
    @required double layoutOffset,
    @required double remainingPaintExtent,
    @required double mainAxisExtent,
    @required double crossAxisExtent,
    @required GrowthDirection growthDirection,
    @required RenderSliver advance(RenderSliver child),
    @required double remainingCacheExtent,
    @required double cacheOrigin,
  }) {
    assert(scrollOffset.isFinite);
    assert(scrollOffset >= 0.0);
    final double initialLayoutOffset = layoutOffset;
    final ScrollDirection adjustedUserScrollDirection =
        applyGrowthDirectionToScrollDirection(offset.userScrollDirection, growthDirection);
    assert(adjustedUserScrollDirection != null);
    double maxPaintOffset = layoutOffset + overlap;
    double precedingScrollExtent = 0.0;

    while (child != null) {
      final double sliverScrollOffset = scrollOffset <= 0.0 ? 0.0 : scrollOffset;
      // If the scrollOffset is too small we adjust the paddedOrigin because it
      // doesn't make sense to ask a sliver for content before its scroll
      // offset.
      final double correctedCacheOrigin = math.max(cacheOrigin, -sliverScrollOffset);
      final double cacheExtentCorrection = cacheOrigin - correctedCacheOrigin;

      assert(sliverScrollOffset >= correctedCacheOrigin.abs());
      assert(correctedCacheOrigin <= 0.0);
      assert(sliverScrollOffset >= 0.0);
      assert(cacheExtentCorrection <= 0.0);
      
      //輸入
      child.layout(SliverConstraints(
        axisDirection: axisDirection,
        growthDirection: growthDirection,
        userScrollDirection: adjustedUserScrollDirection,
        scrollOffset: sliverScrollOffset,
        precedingScrollExtent: precedingScrollExtent,
        overlap: maxPaintOffset - layoutOffset,
        remainingPaintExtent: math.max(0.0, remainingPaintExtent - layoutOffset + initialLayoutOffset),
        crossAxisExtent: crossAxisExtent,
        crossAxisDirection: crossAxisDirection,
        viewportMainAxisExtent: mainAxisExtent,
        remainingCacheExtent: math.max(0.0, remainingCacheExtent + cacheExtentCorrection),
        cacheOrigin: correctedCacheOrigin,
      ), parentUsesSize: true);
      //輸出
      final SliverGeometry childLayoutGeometry = child.geometry;
      assert(childLayoutGeometry.debugAssertIsValid());

      // If there is a correction to apply, we'll have to start over.
      if (childLayoutGeometry.scrollOffsetCorrection != null)
        return childLayoutGeometry.scrollOffsetCorrection;

      // We use the child's paint origin in our coordinate system as the
      // layoutOffset we store in the child's parent data.
      final double effectiveLayoutOffset = layoutOffset + childLayoutGeometry.paintOrigin;

      // `effectiveLayoutOffset` becomes meaningless once we moved past the trailing edge
      // because `childLayoutGeometry.layoutExtent` is zero. Using the still increasing
      // 'scrollOffset` to roughly position these invisible slivers in the right order.
      if (childLayoutGeometry.visible || scrollOffset > 0) {
        updateChildLayoutOffset(child, effectiveLayoutOffset, growthDirection);
      } else {
        updateChildLayoutOffset(child, -scrollOffset + initialLayoutOffset, growthDirection);
      }

      //更新最大繪製位置
      maxPaintOffset = math.max(effectiveLayoutOffset + childLayoutGeometry.paintExtent, maxPaintOffset);
      scrollOffset -= childLayoutGeometry.scrollExtent;
      //前一個child的滾動距離
      precedingScrollExtent += childLayoutGeometry.scrollExtent;
      layoutOffset += childLayoutGeometry.layoutExtent;
      if (childLayoutGeometry.cacheExtent != 0.0) {
        remainingCacheExtent -= childLayoutGeometry.cacheExtent - cacheExtentCorrection;
        cacheOrigin = math.min(correctedCacheOrigin + childLayoutGeometry.cacheExtent, 0.0);
      }
      
      // 更新_maxScrollExtent和_minScrollExtent
      // https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/rendering/viewport.dart#L1449
      updateOutOfBandData(growthDirection, childLayoutGeometry);

      // move on to the next child
      // layout下一個child
      child = advance(child);
    }

    // we made it without a correction, whee!
    //完美,全部的children都沒有錯誤
    return 0.0;
  }
複製程式碼

SliverConstraints為layout child的輸入,SliverGeometry為layout child之後的輸出,layout之後viewport將更新_maxScrollExtent和_minScrollExtent,然後layout下一個sliver。至於child.layout方法裡面內容,我們將會在下一個章當中講到。

RenderShrinkWrappingViewport

當我們把shrinkWrap設定為true的時候,最終的Viewport使用的是RenderShrinkWrappingViewport。那麼我們看看其中的區別是什麼。 先看看官方對shrinkWrap引數的解釋。設定shrinkWrap為true,viewport的大小將不是由它的父親而決定,而是由它自己決定。我們經常碰到由人使用ListView巢狀ListView的情況, 外面的ListView在layout child的時候需要知道里面ListView的大小,而我們前面知道ListView中的Viewport的大小是由它parent告訴它的。

parent:hi, child,你有多大,我給你一個無限縱軸大小的限制。

child: hi, parent,我也不知道啊,你不告訴我,我的viewport有多大。那麼我只能將我的全部child都layout出來才知道我總的大小了。那我得換一個viewport了,RenderShrinkWrappingViewport才能知道計算出我的總高度。

由於ListView的parent無法告訴它的child ListView的可丈量大小,所以我們必須設定shrinkWrap為true,內部使用RenderShrinkWrappingViewport計算。

由於RenderShrinkWrappingViewport的大小不再只由parent決定,所以不再呼叫performResize方法。那麼我們來關注下performLayout方法。

performLayout

 @override
 void performLayout() {
   if (firstChild == null) {
     switch (axis) {
       case Axis.vertical:
         //如果是豎直,你起碼要告訴我水平最大限制吧?
         assert(constraints.hasBoundedWidth);
         size = Size(constraints.maxWidth, constraints.minHeight);
         break;
          //如果是水平,你起碼要告訴我垂直最大限制吧?
       case Axis.horizontal:
         assert(constraints.hasBoundedHeight);
         size = Size(constraints.minWidth, constraints.maxHeight);
         break;
     }
     offset.applyViewportDimension(0.0);
     _maxScrollExtent = 0.0;
     _shrinkWrapExtent = 0.0;
     _hasVisualOverflow = false;
     offset.applyContentDimensions(0.0, 0.0);
     return;
   }

   double mainAxisExtent;
   double crossAxisExtent;
   switch (axis) {
     case Axis.vertical:
      //如果是豎直,你起碼要告訴我水平最大限制吧?說到這個我想起來了Flutter中為啥沒有支援水平和垂直都能滾動的容器了。
       assert(constraints.hasBoundedWidth);
       mainAxisExtent = constraints.maxHeight;
       crossAxisExtent = constraints.maxWidth;
       break;
     case Axis.horizontal:
       assert(constraints.hasBoundedHeight);
       //如果是水平,你起碼要告訴我垂直最大限制吧?
       mainAxisExtent = constraints.maxWidth;
       crossAxisExtent = constraints.maxHeight;
       break;
   }

   double correction;
   double effectiveExtent;
   do {
     assert(offset.pixels != null);
     correction = _attemptLayout(mainAxisExtent, crossAxisExtent, offset.pixels);
     if (correction != 0.0) {
       offset.correctBy(correction);
     } else {
       switch (axis) {
         case Axis.vertical:
           effectiveExtent = constraints.constrainHeight(_shrinkWrapExtent);
           break;
         case Axis.horizontal:
           effectiveExtent = constraints.constrainWidth(_shrinkWrapExtent);
           break;
       }
       final bool didAcceptViewportDimension = offset.applyViewportDimension(effectiveExtent);
       final bool didAcceptContentDimension = offset.applyContentDimensions(0.0, math.max(0.0, _maxScrollExtent - effectiveExtent));
       if (didAcceptViewportDimension && didAcceptContentDimension)
         break;
     }
   } while (true);
   switch (axis) {
     case Axis.vertical:
       size = constraints.constrainDimensions(crossAxisExtent, effectiveExtent);
       break;
     case Axis.horizontal:
       size = constraints.constrainDimensions(effectiveExtent, crossAxisExtent);
       break;
   }
 }
複製程式碼

_maxScrollExtent和 _shrinkWrapExtent都是關鍵先生。當mainAxisExtent不為double.Infinity(無限大)的時候,其實效果跟Viewport裡面計算(除掉Center相關)是一樣; 當mainAxisExtent為double.Infinity(無限大),我們將會將全部的child都layout出來獲得總的大小

關鍵程式碼

 @override
 void updateOutOfBandData(GrowthDirection growthDirection, SliverGeometry childLayoutGeometry) {
   assert(growthDirection == GrowthDirection.forward);
   _maxScrollExtent += childLayoutGeometry.scrollExtent;
   if (childLayoutGeometry.hasVisualOverflow)
     _hasVisualOverflow = true;
   _shrinkWrapExtent += childLayoutGeometry.maxPaintExtent;
 }
複製程式碼

這裡也就是為啥我們之前說Column裡面或者ListView放ListView(子),ListView(子)會全部元素都build,並且失去滾動的原因。

劇透

這一章看起來有些枯燥,都是原始碼分析。下一章(Flutter Sliver一生之敵 (ExtendedList)),我們將順著ListView/GridView=> SliverList/SliverGrid => RenderSliverList/RenderSliverGrid的感情線,瞭解最終Sliver是怎麼將children繪製出來的。下一章將不只是枯燥的原始碼分析,我們將舉一反N,告訴你如何**處理圖片列表記憶體爆炸閃退**,將告訴你列表元素特殊的layout方式等等。

結語

ExtendedList WaterfallFlowLoadingMoreList 都是可以食用的狀態。等不及的小夥伴可以提前食用,特別是圖片列表記憶體過大而導致閃退的小夥伴可以先看demo,先解決掉一直折磨大家的問題

歡迎加入Flutter Candies,一起生產可愛的Flutter小糖果( flutter-candiesQQ群:181398081)

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

Flutter Sliver一生之敵 (ScrollView)

相關文章