sliver_multi_box_adaptor.dart 26.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Adam Barth's avatar
Adam Barth committed
2 3 4 5 6 7 8
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:vector_math/vector_math_64.dart';

9
import 'box.dart';
Adam Barth's avatar
Adam Barth committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import 'object.dart';
import 'sliver.dart';

/// A delegate used by [RenderSliverMultiBoxAdaptor] to manage its children.
///
/// [RenderSliverMultiBoxAdaptor] objects reify their children lazily to avoid
/// spending resources on children that are not visible in the viewport. This
/// delegate lets these objects create and remove children as well as estimate
/// the total scroll offset extent occupied by the full child list.
abstract class RenderSliverBoxChildManager {
  /// Called during layout when a new child is needed. The child should be
  /// inserted into the child list in the appropriate position, after the
  /// `after` child (at the start of the list if `after` is null). Its index and
  /// scroll offsets will automatically be set appropriately.
  ///
  /// The `index` argument gives the index of the child to show. It is possible
  /// for negative indices to be requested. For example: if the user scrolls
  /// from child 0 to child 10, and then those children get much smaller, and
  /// then the user scrolls back up again, this method will eventually be asked
  /// to produce a child for index -1.
  ///
  /// If no child corresponds to `index`, then do nothing.
  ///
  /// Which child is indicated by index zero depends on the [GrowthDirection]
34 35
  /// specified in the `constraints` of the [RenderSliverMultiBoxAdaptor]. For
  /// example if the children are the alphabet, then if
Adam Barth's avatar
Adam Barth committed
36 37
  /// [SliverConstraints.growthDirection] is [GrowthDirection.forward] then
  /// index zero is A, and index 25 is Z. On the other hand if
38 39
  /// [SliverConstraints.growthDirection] is [GrowthDirection.reverse] then
  /// index zero is Z, and index 25 is A.
Adam Barth's avatar
Adam Barth committed
40 41 42 43 44
  ///
  /// During a call to [createChild] it is valid to remove other children from
  /// the [RenderSliverMultiBoxAdaptor] object if they were not created during
  /// this frame and have not yet been updated during this frame. It is not
  /// valid to add any other children to this render object.
45
  void createChild(int index, { required RenderBox? after });
Adam Barth's avatar
Adam Barth committed
46 47 48 49

  /// Remove the given child from the child list.
  ///
  /// Called by [RenderSliverMultiBoxAdaptor.collectGarbage], which itself is
50
  /// called from [RenderSliverMultiBoxAdaptor]'s `performLayout`.
Adam Barth's avatar
Adam Barth committed
51 52 53
  ///
  /// The index of the given child can be obtained using the
  /// [RenderSliverMultiBoxAdaptor.indexOf] method, which reads it from the
54 55
  /// [SliverMultiBoxAdaptorParentData.index] field of the child's
  /// [RenderObject.parentData].
Adam Barth's avatar
Adam Barth committed
56 57 58 59 60 61 62
  void removeChild(RenderBox child);

  /// Called to estimate the total scrollable extents of this object.
  ///
  /// Must return the total distance from the start of the child with the
  /// earliest possible index to the end of the child with the last possible
  /// index.
63 64
  double estimateMaxScrollOffset(
    SliverConstraints constraints, {
65 66 67 68
    int? firstIndex,
    int? lastIndex,
    double? leadingScrollOffset,
    double? trailingScrollOffset,
Adam Barth's avatar
Adam Barth committed
69 70
  });

71 72 73 74 75 76 77 78 79 80 81 82
  /// Called to obtain a precise measure of the total number of children.
  ///
  /// Must return the number that is one greater than the greatest `index` for
  /// which `createChild` will actually create a child.
  ///
  /// This is used when [createChild] cannot add a child for a positive `index`,
  /// to determine the precise dimensions of the sliver. It must return an
  /// accurate and precise non-null value. It will not be called if
  /// [createChild] is always able to create a child (e.g. for an infinite
  /// list).
  int get childCount;

83 84
  /// Called during [RenderSliverMultiBoxAdaptor.adoptChild] or
  /// [RenderSliverMultiBoxAdaptor.move].
Adam Barth's avatar
Adam Barth committed
85 86
  ///
  /// Subclasses must ensure that the [SliverMultiBoxAdaptorParentData.index]
87 88
  /// field of the child's [RenderObject.parentData] accurately reflects the
  /// child's index in the child list after this function returns.
Adam Barth's avatar
Adam Barth committed
89 90
  void didAdoptChild(RenderBox child);

91 92 93 94 95 96 97 98 99 100 101
  /// Called during layout to indicate whether this object provided insufficient
  /// children for the [RenderSliverMultiBoxAdaptor] to fill the
  /// [SliverConstraints.remainingPaintExtent].
  ///
  /// Typically called unconditionally at the start of layout with false and
  /// then later called with true when the [RenderSliverMultiBoxAdaptor]
  /// fails to create a child required to fill the
  /// [SliverConstraints.remainingPaintExtent].
  ///
  /// Useful for subclasses to determine whether newly added children could
  /// affect the visible contents of the [RenderSliverMultiBoxAdaptor].
102 103
  void setDidUnderflow(bool value);

104 105 106 107 108 109 110
  /// Called at the beginning of layout to indicate that layout is about to
  /// occur.
  void didStartLayout() { }

  /// Called at the end of layout to indicate that layout is now complete.
  void didFinishLayout() { }

Adam Barth's avatar
Adam Barth committed
111 112 113 114 115 116 117 118 119 120
  /// In debug mode, asserts that this manager is not expecting any
  /// modifications to the [RenderSliverMultiBoxAdaptor]'s child list.
  ///
  /// This function always returns true.
  ///
  /// The manager is not required to track whether it is expecting modifications
  /// to the [RenderSliverMultiBoxAdaptor]'s child list and can simply return
  /// true without making any assertions.
  bool debugAssertChildListLocked() => true;
}
121 122
/// Parent data structure used by [RenderSliverWithKeepAliveMixin].
mixin KeepAliveParentDataMixin implements ParentData {
123 124 125
  /// Whether to keep the child alive even when it is no longer visible.
  bool keepAlive = false;

126 127
  /// Whether the widget is currently being kept alive, i.e. has [keepAlive] set
  /// to true and is offscreen.
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  bool get keptAlive;
}

/// This class exists to dissociate [KeepAlive] from [RenderSliverMultiBoxAdaptor].
///
/// [RenderSliverWithKeepAliveMixin.setupParentData] must be implemented to use
/// a parentData class that uses the right mixin or whatever is appropriate.
mixin RenderSliverWithKeepAliveMixin implements RenderSliver {
  /// Alerts the developer that the child's parentData needs to be of type
  /// [KeepAliveParentDataMixin].
  @override
  void setupParentData(RenderObject child) {
    assert(child.parentData is KeepAliveParentDataMixin);
  }
}

/// Parent data structure used by [RenderSliverMultiBoxAdaptor].
class SliverMultiBoxAdaptorParentData extends SliverLogicalParentData with ContainerParentDataMixin<RenderBox>, KeepAliveParentDataMixin {
  /// The index of this child according to the [RenderSliverBoxChildManager].
147
  int? index;
148 149

  @override
150
  bool get keptAlive => _keptAlive;
151 152
  bool _keptAlive = false;

Adam Barth's avatar
Adam Barth committed
153
  @override
154
  String toString() => 'index=$index; ${keepAlive == true ? "keepAlive; " : ""}${super.toString()}';
Adam Barth's avatar
Adam Barth committed
155 156
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170
/// A sliver with multiple box children.
///
/// [RenderSliverMultiBoxAdaptor] is a base class for slivers that have multiple
/// box children. The children are managed by a [RenderSliverBoxChildManager],
/// which lets subclasses create children lazily during layout. Typically
/// subclasses will create only those children that are actually needed to fill
/// the [SliverConstraints.remainingPaintExtent].
///
/// The contract for adding and removing children from this render object is
/// more strict than for normal render objects:
///
/// * Children can be removed except during a layout pass if they have already
///   been laid out during that layout pass.
/// * Children cannot be added except during a call to [childManager], and
171
///   then only if there is no child corresponding to that index (or the child
172 173 174 175 176 177 178 179 180 181
///   child corresponding to that index was first removed).
///
/// See also:
///
///  * [RenderSliverToBoxAdapter], which has a single box child.
///  * [RenderSliverList], which places its children in a linear
///    array.
///  * [RenderSliverFixedExtentList], which places its children in a linear
///    array with a fixed extent in the main axis.
///  * [RenderSliverGrid], which places its children in arbitrary positions.
Adam Barth's avatar
Adam Barth committed
182 183
abstract class RenderSliverMultiBoxAdaptor extends RenderSliver
  with ContainerRenderObjectMixin<RenderBox, SliverMultiBoxAdaptorParentData>,
184
       RenderSliverHelpers, RenderSliverWithKeepAliveMixin {
Adam Barth's avatar
Adam Barth committed
185

186 187 188
  /// Creates a sliver with multiple box children.
  ///
  /// The [childManager] argument must not be null.
Adam Barth's avatar
Adam Barth committed
189
  RenderSliverMultiBoxAdaptor({
190
    required RenderSliverBoxChildManager childManager,
191
  }) : assert(childManager != null),
192 193 194 195 196 197
       _childManager = childManager {
    assert(() {
      _debugDanglingKeepAlives = <RenderBox>[];
      return true;
    }());
  }
Adam Barth's avatar
Adam Barth committed
198 199 200 201

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! SliverMultiBoxAdaptorParentData)
202
      child.parentData = SliverMultiBoxAdaptorParentData();
Adam Barth's avatar
Adam Barth committed
203 204
  }

205 206 207 208 209 210
  /// The delegate that manages the children of this object.
  ///
  /// Rather than having a concrete list of children, a
  /// [RenderSliverMultiBoxAdaptor] uses a [RenderSliverBoxChildManager] to
  /// create children during layout in order to fill the
  /// [SliverConstraints.remainingPaintExtent].
Adam Barth's avatar
Adam Barth committed
211 212 213 214
  @protected
  RenderSliverBoxChildManager get childManager => _childManager;
  final RenderSliverBoxChildManager _childManager;

215 216 217
  /// The nodes being kept alive despite not being visible.
  final Map<int, RenderBox> _keepAliveBucket = <int, RenderBox>{};

218
  late List<RenderBox> _debugDanglingKeepAlives;
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

  /// Indicates whether integrity check is enabled.
  ///
  /// Setting this property to true will immediately perform an integrity check.
  ///
  /// The integrity check consists of:
  ///
  /// 1. Verify that the children index in childList is in ascending order.
  /// 2. Verify that there is no dangling keepalive child as the result of [move].
  bool get debugChildIntegrityEnabled => _debugChildIntegrityEnabled;
  bool _debugChildIntegrityEnabled = true;
  set debugChildIntegrityEnabled(bool enabled) {
    assert(enabled != null);
    assert(() {
      _debugChildIntegrityEnabled = enabled;
      return _debugVerifyChildOrder() &&
        (!_debugChildIntegrityEnabled || _debugDanglingKeepAlives.isEmpty);
    }());
  }

Adam Barth's avatar
Adam Barth committed
239 240 241
  @override
  void adoptChild(RenderObject child) {
    super.adoptChild(child);
242
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
243
    if (!childParentData._keptAlive)
244
      childManager.didAdoptChild(child as RenderBox);
Adam Barth's avatar
Adam Barth committed
245 246 247 248
  }

  bool _debugAssertChildListLocked() => childManager.debugAssertChildListLocked();

249 250 251 252 253
  /// Verify that the child list index is in strictly increasing order.
  ///
  /// This has no effect in release builds.
  bool _debugVerifyChildOrder(){
    if (_debugChildIntegrityEnabled) {
254
      RenderBox? child = firstChild;
255 256 257 258 259 260 261 262 263 264
      int index;
      while (child != null) {
        index = indexOf(child);
        child = childAfter(child);
        assert(child == null || indexOf(child) > index);
      }
    }
    return true;
  }

Adam Barth's avatar
Adam Barth committed
265
  @override
266
  void insert(RenderBox child, { RenderBox? after }) {
267
    assert(!_keepAliveBucket.containsValue(child));
Adam Barth's avatar
Adam Barth committed
268 269
    super.insert(child, after: after);
    assert(firstChild != null);
270 271 272 273
    assert(_debugVerifyChildOrder());
  }

  @override
274
  void move(RenderBox child, { RenderBox? after }) {
275 276 277 278 279 280 281 282 283
    // There are two scenarios:
    //
    // 1. The child is not keptAlive.
    // The child is in the childList maintained by ContainerRenderObjectMixin.
    // We can call super.move and update parentData with the new slot.
    //
    // 2. The child is keptAlive.
    // In this case, the child is no longer in the childList but might be stored in
    // [_keepAliveBucket]. We need to update the location of the child in the bucket.
284
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
285 286 287 288 289 290 291 292 293 294 295
    if (!childParentData.keptAlive) {
      super.move(child, after: after);
      childManager.didAdoptChild(child); // updates the slot in the parentData
      // Its slot may change even if super.move does not change the position.
      // In this case, we still want to mark as needs layout.
      markNeedsLayout();
    } else {
      // If the child in the bucket is not current child, that means someone has
      // already moved and replaced current child, and we cannot remove this child.
      if (_keepAliveBucket[childParentData.index] == child) {
        _keepAliveBucket.remove(childParentData.index);
Adam Barth's avatar
Adam Barth committed
296
      }
297 298 299 300 301 302 303 304 305 306 307
      assert(() {
        _debugDanglingKeepAlives.remove(child);
        return true;
      }());
      // Update the slot and reinsert back to _keepAliveBucket in the new slot.
      childManager.didAdoptChild(child);
      // If there is an existing child in the new slot, that mean that child will
      // be moved to other index. In other cases, the existing child should have been
      // removed by updateChild. Thus, it is ok to overwrite it.
      assert(() {
        if (_keepAliveBucket.containsKey(childParentData.index))
308
          _debugDanglingKeepAlives.add(_keepAliveBucket[childParentData.index]!);
309 310
        return true;
      }());
311
      _keepAliveBucket[childParentData.index!] = child;
312
    }
Adam Barth's avatar
Adam Barth committed
313 314
  }

315 316
  @override
  void remove(RenderBox child) {
317
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
318 319 320 321 322
    if (!childParentData._keptAlive) {
      super.remove(child);
      return;
    }
    assert(_keepAliveBucket[childParentData.index] == child);
323 324 325 326
    assert(() {
      _debugDanglingKeepAlives.remove(child);
      return true;
    }());
327 328 329 330 331 332 333
    _keepAliveBucket.remove(childParentData.index);
    dropChild(child);
  }

  @override
  void removeAll() {
    super.removeAll();
334
    _keepAliveBucket.values.forEach(dropChild);
335 336 337
    _keepAliveBucket.clear();
  }

338
  void _createOrObtainChild(int index, { required RenderBox? after }) {
339 340 341
    invokeLayoutCallback<SliverConstraints>((SliverConstraints constraints) {
      assert(constraints == this.constraints);
      if (_keepAliveBucket.containsKey(index)) {
342
        final RenderBox child = _keepAliveBucket.remove(index)!;
343
        final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
344 345 346 347 348 349 350 351 352 353 354 355
        assert(childParentData._keptAlive);
        dropChild(child);
        child.parentData = childParentData;
        insert(child, after: after);
        childParentData._keptAlive = false;
      } else {
        _childManager.createChild(index, after: after);
      }
    });
  }

  void _destroyOrCacheChild(RenderBox child) {
356
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
357 358 359
    if (childParentData.keepAlive) {
      assert(!childParentData._keptAlive);
      remove(child);
360
      _keepAliveBucket[childParentData.index!] = child;
361 362 363 364 365 366 367 368 369 370 371 372 373
      child.parentData = childParentData;
      super.adoptChild(child);
      childParentData._keptAlive = true;
    } else {
      assert(child.parent == this);
      _childManager.removeChild(child);
      assert(child.parent == null);
    }
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
374
    for (final RenderBox child in _keepAliveBucket.values)
375 376 377 378 379 380
      child.attach(owner);
  }

  @override
  void detach() {
    super.detach();
381
    for (final RenderBox child in _keepAliveBucket.values)
382 383 384 385 386 387
      child.detach();
  }

  @override
  void redepthChildren() {
    super.redepthChildren();
388
    _keepAliveBucket.values.forEach(redepthChild);
389 390 391 392 393
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    super.visitChildren(visitor);
394
    _keepAliveBucket.values.forEach(visitor);
395 396
  }

397 398 399 400 401 402
  @override
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
    super.visitChildren(visitor);
    // Do not visit children in [_keepAliveBucket].
  }

Adam Barth's avatar
Adam Barth committed
403 404 405 406
  /// Called during layout to create and add the child with the given index and
  /// scroll offset.
  ///
  /// Calls [RenderSliverBoxChildManager.createChild] to actually create and add
407 408
  /// the child if necessary. The child may instead be obtained from a cache;
  /// see [SliverMultiBoxAdaptorParentData.keepAlive].
Adam Barth's avatar
Adam Barth committed
409
  ///
410 411
  /// Returns false if there was no cached child and `createChild` did not add
  /// any child, otherwise returns true.
Adam Barth's avatar
Adam Barth committed
412 413 414
  ///
  /// Does not layout the new child.
  ///
415 416 417 418
  /// When this is called, there are no visible children, so no children can be
  /// removed during the call to `createChild`. No child should be added during
  /// that call either, except for the one that is created and returned by
  /// `createChild`.
Adam Barth's avatar
Adam Barth committed
419
  @protected
420
  bool addInitialChild({ int index = 0, double layoutOffset = 0.0 }) {
Adam Barth's avatar
Adam Barth committed
421 422
    assert(_debugAssertChildListLocked());
    assert(firstChild == null);
423 424 425
    _createOrObtainChild(index, after: null);
    if (firstChild != null) {
      assert(firstChild == lastChild);
426 427
      assert(indexOf(firstChild!) == index);
      final SliverMultiBoxAdaptorParentData firstChildParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
428 429 430 431 432
      firstChildParentData.layoutOffset = layoutOffset;
      return true;
    }
    childManager.setDidUnderflow(true);
    return false;
Adam Barth's avatar
Adam Barth committed
433 434 435 436 437 438
  }

  /// Called during layout to create, add, and layout the child before
  /// [firstChild].
  ///
  /// Calls [RenderSliverBoxChildManager.createChild] to actually create and add
439 440
  /// the child if necessary. The child may instead be obtained from a cache;
  /// see [SliverMultiBoxAdaptorParentData.keepAlive].
Adam Barth's avatar
Adam Barth committed
441
  ///
442
  /// Returns the new child or null if no child was obtained.
Adam Barth's avatar
Adam Barth committed
443 444 445 446
  ///
  /// The child that was previously the first child, as well as any subsequent
  /// children, may be removed by this call if they have not yet been laid out
  /// during this layout pass. No child should be added during that call except
447
  /// for the one that is created and returned by `createChild`.
Adam Barth's avatar
Adam Barth committed
448
  @protected
449
  RenderBox? insertAndLayoutLeadingChild(
450
    BoxConstraints childConstraints, {
451
    bool parentUsesSize = false,
Adam Barth's avatar
Adam Barth committed
452 453
  }) {
    assert(_debugAssertChildListLocked());
454
    final int index = indexOf(firstChild!) - 1;
455
    _createOrObtainChild(index, after: null);
456 457
    if (indexOf(firstChild!) == index) {
      firstChild!.layout(childConstraints, parentUsesSize: parentUsesSize);
Adam Barth's avatar
Adam Barth committed
458 459
      return firstChild;
    }
460
    childManager.setDidUnderflow(true);
Adam Barth's avatar
Adam Barth committed
461 462 463 464 465 466 467
    return null;
  }

  /// Called during layout to create, add, and layout the child after
  /// the given child.
  ///
  /// Calls [RenderSliverBoxChildManager.createChild] to actually create and add
468 469
  /// the child if necessary. The child may instead be obtained from a cache;
  /// see [SliverMultiBoxAdaptorParentData.keepAlive].
Adam Barth's avatar
Adam Barth committed
470 471 472 473 474 475 476
  ///
  /// Returns the new child. It is the responsibility of the caller to configure
  /// the child's scroll offset.
  ///
  /// Children after the `after` child may be removed in the process. Only the
  /// new child may be added.
  @protected
477
  RenderBox? insertAndLayoutChild(
478
    BoxConstraints childConstraints, {
479
    required RenderBox? after,
480
    bool parentUsesSize = false,
Adam Barth's avatar
Adam Barth committed
481 482 483
  }) {
    assert(_debugAssertChildListLocked());
    assert(after != null);
484
    final int index = indexOf(after!) + 1;
485
    _createOrObtainChild(index, after: after);
486
    final RenderBox? child = childAfter(after);
Adam Barth's avatar
Adam Barth committed
487 488 489 490
    if (child != null && indexOf(child) == index) {
      child.layout(childConstraints, parentUsesSize: parentUsesSize);
      return child;
    }
491
    childManager.setDidUnderflow(true);
Adam Barth's avatar
Adam Barth committed
492 493 494 495 496
    return null;
  }

  /// Called after layout with the number of children that can be garbage
  /// collected at the head and tail of the child list.
497 498 499 500 501 502 503
  ///
  /// Children whose [SliverMultiBoxAdaptorParentData.keepAlive] property is
  /// set to true will be removed to a cache instead of being dropped.
  ///
  /// This method also collects any children that were previously kept alive but
  /// are now no longer necessary. As such, it should be called every time
  /// [performLayout] is run, even if the arguments are both zero.
Adam Barth's avatar
Adam Barth committed
504 505 506 507 508 509
  @protected
  void collectGarbage(int leadingGarbage, int trailingGarbage) {
    assert(_debugAssertChildListLocked());
    assert(childCount >= leadingGarbage + trailingGarbage);
    invokeLayoutCallback<SliverConstraints>((SliverConstraints constraints) {
      while (leadingGarbage > 0) {
510
        _destroyOrCacheChild(firstChild!);
Adam Barth's avatar
Adam Barth committed
511 512 513
        leadingGarbage -= 1;
      }
      while (trailingGarbage > 0) {
514
        _destroyOrCacheChild(lastChild!);
Adam Barth's avatar
Adam Barth committed
515 516
        trailingGarbage -= 1;
      }
517 518 519 520
      // Ask the child manager to remove the children that are no longer being
      // kept alive. (This should cause _keepAliveBucket to change, so we have
      // to prepare our list ahead of time.)
      _keepAliveBucket.values.where((RenderBox child) {
521
        final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
522 523 524
        return !childParentData.keepAlive;
      }).toList().forEach(_childManager.removeChild);
      assert(_keepAliveBucket.values.where((RenderBox child) {
525
        final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
526 527
        return !childParentData.keepAlive;
      }).isEmpty);
Adam Barth's avatar
Adam Barth committed
528 529 530 531 532 533 534
    });
  }

  /// Returns the index of the given child, as given by the
  /// [SliverMultiBoxAdaptorParentData.index] field of the child's [parentData].
  int indexOf(RenderBox child) {
    assert(child != null);
535
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
Adam Barth's avatar
Adam Barth committed
536
    assert(childParentData.index != null);
537
    return childParentData.index!;
Adam Barth's avatar
Adam Barth committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  }

  /// Returns the dimension of the given child in the main axis, as given by the
  /// child's [RenderBox.size] property. This is only valid after layout.
  @protected
  double paintExtentOf(RenderBox child) {
    assert(child != null);
    assert(child.hasSize);
    switch (constraints.axis) {
      case Axis.horizontal:
        return child.size.width;
      case Axis.vertical:
        return child.size.height;
    }
  }

  @override
555 556
  bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
    RenderBox? child = lastChild;
557
    final BoxHitTestResult boxResult = BoxHitTestResult.wrap(result);
Adam Barth's avatar
Adam Barth committed
558
    while (child != null) {
559
      if (hitTestBoxChild(boxResult, child, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition))
Adam Barth's avatar
Adam Barth committed
560 561 562 563 564 565 566
        return true;
      child = childBefore(child);
    }
    return false;
  }

  @override
567
  double childMainAxisPosition(RenderBox child) {
568
    return childScrollOffset(child)! - constraints.scrollOffset;
569 570 571
  }

  @override
572
  double? childScrollOffset(RenderObject child) {
573 574
    assert(child != null);
    assert(child.parent == this);
575
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
576
    return childParentData.layoutOffset;
Adam Barth's avatar
Adam Barth committed
577 578 579
  }

  @override
580 581 582 583 584 585 586 587 588 589
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
    if (_keepAliveBucket.containsKey(indexOf(child))) {
      // It is possible that widgets under kept alive children want to paint
      // themselves. For example, the Material widget tries to paint all
      // InkFeatures under its subtree as long as they are not disposed. In
      // such case, we give it a zero transform to prevent them from painting.
      transform.setZero();
    } else {
      applyPaintTransformForBoxChild(child, transform);
    }
Adam Barth's avatar
Adam Barth committed
590 591 592 593 594 595 596 597
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (firstChild == null)
      return;
    // offset is to the top-left corner, regardless of our axis direction.
    // originOffset gives us the delta from the real origin to the origin in the axis direction.
598
    Offset mainAxisUnit, crossAxisUnit, originOffset;
Adam Barth's avatar
Adam Barth committed
599 600 601
    bool addExtent;
    switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
      case AxisDirection.up:
602 603
        mainAxisUnit = const Offset(0.0, -1.0);
        crossAxisUnit = const Offset(1.0, 0.0);
604
        originOffset = offset + Offset(0.0, geometry!.paintExtent);
Adam Barth's avatar
Adam Barth committed
605 606 607
        addExtent = true;
        break;
      case AxisDirection.right:
608 609
        mainAxisUnit = const Offset(1.0, 0.0);
        crossAxisUnit = const Offset(0.0, 1.0);
Adam Barth's avatar
Adam Barth committed
610 611 612 613
        originOffset = offset;
        addExtent = false;
        break;
      case AxisDirection.down:
614 615
        mainAxisUnit = const Offset(0.0, 1.0);
        crossAxisUnit = const Offset(1.0, 0.0);
Adam Barth's avatar
Adam Barth committed
616 617 618 619
        originOffset = offset;
        addExtent = false;
        break;
      case AxisDirection.left:
620 621
        mainAxisUnit = const Offset(-1.0, 0.0);
        crossAxisUnit = const Offset(0.0, 1.0);
622
        originOffset = offset + Offset(geometry!.paintExtent, 0.0);
Adam Barth's avatar
Adam Barth committed
623 624 625
        addExtent = true;
        break;
    }
626
    assert(mainAxisUnit != null);
Adam Barth's avatar
Adam Barth committed
627
    assert(addExtent != null);
628
    RenderBox? child = firstChild;
Adam Barth's avatar
Adam Barth committed
629
    while (child != null) {
630 631
      final double mainAxisDelta = childMainAxisPosition(child);
      final double crossAxisDelta = childCrossAxisPosition(child);
632
      Offset childOffset = Offset(
633 634 635
        originOffset.dx + mainAxisUnit.dx * mainAxisDelta + crossAxisUnit.dx * crossAxisDelta,
        originOffset.dy + mainAxisUnit.dy * mainAxisDelta + crossAxisUnit.dy * crossAxisDelta,
      );
Adam Barth's avatar
Adam Barth committed
636
      if (addExtent)
637
        childOffset += mainAxisUnit * paintExtentOf(child);
638

639
      // If the child's visible interval (mainAxisDelta, mainAxisDelta + paintExtentOf(child))
640
      // does not intersect the paint extent interval (0, constraints.remainingPaintExtent), it's hidden.
641
      if (mainAxisDelta < constraints.remainingPaintExtent && mainAxisDelta + paintExtentOf(child) > 0)
642 643
        context.paintChild(child, childOffset);

Adam Barth's avatar
Adam Barth committed
644 645 646 647 648
      child = childAfter(child);
    }
  }

  @override
649 650
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
651
    properties.add(DiagnosticsNode.message(firstChild != null ? 'currently live children: ${indexOf(firstChild!)} to ${indexOf(lastChild!)}' : 'no children current live'));
Adam Barth's avatar
Adam Barth committed
652 653
  }

654 655 656 657
  /// Asserts that the reified child list is not empty and has a contiguous
  /// sequence of indices.
  ///
  /// Always returns true.
Adam Barth's avatar
Adam Barth committed
658 659 660
  bool debugAssertChildListIsNonEmptyAndContiguous() {
    assert(() {
      assert(firstChild != null);
661 662
      int index = indexOf(firstChild!);
      RenderBox? child = childAfter(firstChild!);
Adam Barth's avatar
Adam Barth committed
663 664 665 666 667 668
      while (child != null) {
        index += 1;
        assert(indexOf(child) == index);
        child = childAfter(child);
      }
      return true;
669
    }());
Adam Barth's avatar
Adam Barth committed
670 671
    return true;
  }
672 673

  @override
674 675
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> children = <DiagnosticsNode>[];
676
    if (firstChild != null) {
677
      RenderBox? child = firstChild;
678
      while (true) {
679
        final SliverMultiBoxAdaptorParentData childParentData = child!.parentData as SliverMultiBoxAdaptorParentData;
680
        children.add(child.toDiagnosticsNode(name: 'child with index ${childParentData.index}'));
681 682
        if (child == lastChild)
          break;
683 684 685 686 687
        child = childParentData.nextSibling;
      }
    }
    if (_keepAliveBucket.isNotEmpty) {
      final List<int> indices = _keepAliveBucket.keys.toList()..sort();
688
      for (final int index in indices) {
689
        children.add(_keepAliveBucket[index]!.toDiagnosticsNode(
690
          name: 'child with index $index (kept alive but not laid out)',
691 692
          style: DiagnosticsTreeStyle.offstage,
        ));
693 694
      }
    }
695
    return children;
696
  }
697
}