mixed_viewport.dart 25.1 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:collection';

7
import 'package:flutter/rendering.dart';
8 9 10

import 'framework.dart';
import 'basic.dart';
11

12 13 14 15 16 17 18 19 20
typedef Widget IndexedBuilder(BuildContext context, int index); // return null if index is greater than index of last entry
typedef void InvalidatorCallback(Iterable<int> indices);
typedef void InvalidatorAvailableCallback(InvalidatorCallback invalidator);

enum _ChangeDescription { none, scrolled, resized }

class MixedViewport extends RenderObjectWidget {
  MixedViewport({
    Key key,
21
    this.startOffset: 0.0,
22
    this.direction: Axis.vertical,
23 24
    this.builder,
    this.token,
25
    this.onPaintOffsetUpdateNeeded,
26
    this.onInvalidatorAvailable
27
  }) : super(key: key);
28 29

  final double startOffset;
30
  final Axis direction;
31
  final IndexedBuilder builder;
32
  final Object token; // change this if the list changed (i.e. there are added, removed, or resorted items)
33
  final ViewportDimensionsChangeCallback onPaintOffsetUpdateNeeded;
34
  final InvalidatorAvailableCallback onInvalidatorAvailable; // call the callback this gives to invalidate sizes
35

36
  _MixedViewportElement createElement() => new _MixedViewportElement(this);
37 38 39

  // we don't pass constructor arguments to the RenderBlockViewport() because until
  // we know our children, the constructor arguments we could give have no effect
40
  RenderBlockViewport createRenderObject(BuildContext context) => new RenderBlockViewport();
41 42 43 44 45 46 47 48 49 50 51 52 53

  _ChangeDescription evaluateChangesFrom(MixedViewport oldWidget) {
    if (direction != oldWidget.direction ||
        builder != oldWidget.builder ||
        token != oldWidget.token)
      return _ChangeDescription.resized;
    if (startOffset != oldWidget.startOffset)
      return _ChangeDescription.scrolled;
    return _ChangeDescription.none;
  }

  // all the actual work is done in the element
}
54

55 56 57
class _ChildKey {
  const _ChildKey(this.type, this.key);
  factory _ChildKey.fromWidget(Widget widget) => new _ChildKey(widget.runtimeType, widget.key);
58
  final Type type;
59
  final Key key;
Hixie's avatar
Hixie committed
60 61 62 63 64 65 66
  bool operator ==(dynamic other) {
    if (other is! _ChildKey)
      return false;
    final _ChildKey typedOther = other;
    return type == typedOther.type &&
           key == typedOther.key;
  }
67
  int get hashCode => hashValues(type, key);
68
  String toString() => "_ChildKey(type: $type, key: $key)";
69 70
}

71
class _MixedViewportElement extends RenderObjectElement {
72
  _MixedViewportElement(MixedViewport widget) : super(widget) {
73 74
    if (widget.onInvalidatorAvailable != null)
      widget.onInvalidatorAvailable(invalidate);
75 76
  }

77 78
  MixedViewport get widget => super.widget;

79 80 81
  /// _childExtents contains the extents of each child from the top of the list
  /// up to the last one we've ever created.
  final List<double> _childExtents = <double>[];
82

83 84 85 86 87 88 89 90
  /// _childOffsets contains the offsets of the top of each child from the top
  /// of the list up to the last one we've ever created, and the offset of the
  /// end of the last one. The first value is always 0.0. If there are no
  /// children, that is the only value. The offset of the end of the last child
  /// created (the actual last child, if didReachLastChild is true), is also the
  /// distance from the top (left) of the first child to the bottom (right) of
  /// the last child created.
  final List<double> _childOffsets = <double>[0.0];
91

92 93
  /// Whether childOffsets includes the offset of the last child.
  bool _didReachLastChild = false;
94

95 96 97
  /// The index of the first child whose bottom edge is below the top of the
  /// viewport.
  int _firstVisibleChildIndex;
98

99 100
  /// The currently visibly children.
  Map<_ChildKey, Element> _childrenByKey = new Map<_ChildKey, Element>();
101

102
  /// The child offsets that we've been told are invalid.
103
  final Set<int> _invalidIndices = new HashSet<int>();
104

105 106
  /// Returns false if any of the previously-cached offsets have been marked as
  /// invalid and need to be updated.
Adam Barth's avatar
Adam Barth committed
107
  bool get _isValid => _invalidIndices.isEmpty;
108

109 110
  /// The constraints for which the current offsets are valid.
  BoxConstraints _lastLayoutConstraints;
111

112 113 114 115 116
  /// The last value that was sent to onPaintOffsetUpdateNeeded.
  ViewportDimensions _lastReportedDimensions;

  double _overrideStartOffset;
  double get startOffset => _overrideStartOffset ?? widget.startOffset;
117

118
  RenderBlockViewport get renderObject => super.renderObject;
119

120 121 122 123 124 125 126 127
  /// Notify the BlockViewport that the children at indices have, or might have,
  /// changed size. Call this whenever the dimensions of a particular child
  /// change, so that the rendering will be updated accordingly. A pointer to
  /// this method is provided via the onInvalidatorAvailable callback.
  void invalidate(Iterable<int> indices) {
    assert(indices.length > 0);
    _invalidIndices.addAll(indices);
    renderObject.markNeedsLayout();
128 129
  }

130 131 132 133 134 135 136
  /// Forget all the known child offsets.
  void _resetCache() {
    _childExtents.clear();
    _childOffsets.clear();
    _childOffsets.add(0.0);
    _didReachLastChild = false;
    _invalidIndices.clear();
137
  }
138

139 140 141
  void visitChildren(ElementVisitor visitor) {
    for (Element child in _childrenByKey.values)
      visitor(child);
142 143
  }

144 145
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
Adam Barth's avatar
Adam Barth committed
146 147 148
    renderObject
      ..direction = widget.direction
      ..callback = layout
149
      ..postLayoutCallback = postLayout
Adam Barth's avatar
Adam Barth committed
150 151 152
      ..totalExtentCallback = _noIntrinsicExtent
      ..maxCrossAxisExtentCallback = _noIntrinsicExtent
      ..minCrossAxisExtentCallback = _noIntrinsicExtent;
153 154
  }

155
  void unmount() {
Adam Barth's avatar
Adam Barth committed
156 157
    renderObject
      ..callback = null
158
      ..postLayoutCallback = null
Adam Barth's avatar
Adam Barth committed
159 160 161
      ..totalExtentCallback = null
      ..minCrossAxisExtentCallback = null
      ..maxCrossAxisExtentCallback = null;
162
    super.unmount();
163 164
  }

165
  double _noIntrinsicExtent(BoxConstraints constraints) {
166
    assert(() {
167 168 169 170 171 172 173 174
      if (!RenderObject.debugCheckingIntrinsics) {
        throw new UnsupportedError(
          'MixedViewport does not support returning intrinsic dimensions.\n'
          'Calculating the intrinsic dimensions would require walking the entire child list,\n'
          'which defeats the entire point of having a lazily-built list of children.'
        );
      }
      return true;
175 176 177 178
    });
    return null;
  }

Adam Barth's avatar
Adam Barth committed
179
  static final Object _omit = new Object(); // used as a slot when it's not yet time to attach the child
180 181 182 183

  void update(MixedViewport newWidget) {
    _ChangeDescription changes = newWidget.evaluateChangesFrom(widget);
    super.update(newWidget);
Adam Barth's avatar
Adam Barth committed
184
    renderObject.direction = widget.direction;
185
    _overrideStartOffset = null;
186 187
    if (changes == _ChangeDescription.resized)
      _resetCache();
Adam Barth's avatar
Adam Barth committed
188
    if (changes != _ChangeDescription.none || !_isValid) {
189
      // we scrolled or changed in some other potentially layout-affecting way
190 191
      renderObject.markNeedsLayout();
    } else {
192 193 194 195 196
      // We have to reinvoke our builders because they might return new data.
      // Consider a stateful component that owns us. The builder it gives us
      // includes some of the state from that component. The component calls
      // setState() on itself. It rebuilds. Part of that involves rebuilding
      // us, but now what? If we don't reinvoke the builders. then they will
197 198 199 200 201
      // not be rebuilt, and so the new state won't be used. Therefore, we use
      // the object identity of the widget to determine whether to reinvoke the
      // builders.
      //
      // If the builders are to change so much that the _sizes_ of
202 203
      // the children would change, then the parent must change the 'token'.
      if (!renderObject.needsLayout)
204
        performRebuild();
205 206 207
    }
  }

208
  void performRebuild() {
209 210 211 212 213 214
    // we just need to redraw our existing widgets as-is
    if (_childrenByKey.length > 0) {
      assert(_firstVisibleChildIndex >= 0);
      assert(renderObject != null);
      final int startIndex = _firstVisibleChildIndex;
      int lastIndex = startIndex + _childrenByKey.length - 1;
Ian Hickson's avatar
Ian Hickson committed
215
      Element previousChild;
Adam Barth's avatar
Adam Barth committed
216
      for (int index = startIndex; index <= lastIndex; index += 1) {
217 218 219 220
        final Widget newWidget = _buildWidgetAt(index);
        final _ChildKey key = new _ChildKey.fromWidget(newWidget);
        final Element oldElement = _childrenByKey[key];
        assert(oldElement != null);
Adam Barth's avatar
Adam Barth committed
221
        final Element newElement = updateChild(oldElement, newWidget, previousChild);
222 223 224 225 226 227
        assert(newElement != null);
        _childrenByKey[key] = newElement;
        // Verify that it hasn't changed size.
        // If this assertion fires, it means you didn't call "invalidate"
        // before changing the size of one of your items.
        assert(_debugIsSameSize(newElement, index, _lastLayoutConstraints));
Adam Barth's avatar
Adam Barth committed
228
        previousChild = newElement;
229 230
      }
    }
231
    super.performRebuild();
232 233 234 235 236 237 238 239 240
  }

  void layout(BoxConstraints constraints) {
    if (constraints != _lastLayoutConstraints) {
      _resetCache();
      _lastLayoutConstraints = constraints;
    }
    BuildableElement.lockState(() {
      _doLayout(constraints);
241
    }, building: true);
242 243 244 245 246 247 248 249 250
  }

  void postLayout() {
    assert(renderObject.hasSize);
    if (widget.onPaintOffsetUpdateNeeded != null) {
      final Size containerSize = renderObject.size;
      final double newExtent = _didReachLastChild ? _childOffsets.last : double.INFINITY;
      Size contentSize;
      switch (widget.direction) {
251
        case Axis.vertical:
252 253 254 255 256
          contentSize = new Size(containerSize.width, newExtent);
          break;
        case Axis.horizontal:
          contentSize = new Size(newExtent, containerSize.height);
          break;
257
      }
258 259 260 261 262 263 264 265
      ViewportDimensions dimensions = new ViewportDimensions(
        containerSize: containerSize,
        contentSize: contentSize
      );
      if (dimensions != _lastReportedDimensions) {
        _lastReportedDimensions = dimensions;
        Offset overrideOffset = widget.onPaintOffsetUpdateNeeded(dimensions);
        switch (widget.direction) {
266
          case Axis.vertical:
267 268 269 270 271 272 273 274 275 276 277 278 279 280
            assert(overrideOffset.dx == 0.0);
            _overrideStartOffset = overrideOffset.dy;
            break;
          case Axis.horizontal:
            assert(overrideOffset.dy == 0.0);
            _overrideStartOffset = overrideOffset.dx;
            break;
        }
      }
    }
    if (_childOffsets.length > 0) {
      renderObject.startOffset = _childOffsets[_firstVisibleChildIndex] - startOffset;
    } else {
      renderObject.startOffset = 0.0;
281 282 283 284
    }
  }

  /// Binary search to find the index of the child responsible for rendering a given pixel
285 286
  int _findIndexForOffsetBeforeOrAt(double offset) {
    int left = 0;
287
    int right = _childOffsets.length - 1;
288 289
    while (right >= left) {
      int middle = left + ((right - left) ~/ 2);
290
      if (_childOffsets[middle] < offset) {
291
        left = middle + 1;
292
      } else if (_childOffsets[middle] > offset) {
293 294 295 296 297 298 299 300
        right = middle - 1;
      } else {
        return middle;
      }
    }
    return right;
  }

301 302 303 304 305
  /// Calls the builder. This is for the case where you don't know if you have a child at this index.
  Widget _maybeBuildWidgetAt(int index) {
    if (widget.builder == null)
      return null;
    final Widget newWidget = widget.builder(this, index);
306 307 308 309
    assert(() {
      'Every widget in a list must have a list-unique key.';
      return newWidget == null || newWidget.key != null;
    });
310
    return newWidget;
311 312
  }

313 314 315
  /// Calls the builder. This is for the case where you know that you should have a child there.
  Widget _buildWidgetAt(int index) {
    final Widget newWidget = widget.builder(this, index);
316
    assert(newWidget != null);
317
    assert(newWidget.key != null); // every widget in a list must have a list-unique key
318 319 320
    return newWidget;
  }

321 322 323 324 325 326 327 328 329 330 331 332 333 334
  /// Given an element configuration, inflates the element, updating the existing one if there was one.
  /// Returns the resulting element.
  Element _inflateOrUpdateWidget(Widget newWidget) {
    final _ChildKey key = new _ChildKey.fromWidget(newWidget);
    final Element oldElement = _childrenByKey[key];
    final Element newElement = updateChild(oldElement, newWidget, _omit);
    assert(newElement != null);
    return newElement;
  }

  // Build the widget at index.
  Element _getElement(int index, BoxConstraints innerConstraints) {
    assert(index <= _childOffsets.length - 1);
    final Widget newWidget = _buildWidgetAt(index);
Adam Barth's avatar
Adam Barth committed
335
    return _inflateOrUpdateWidget(newWidget);
336 337 338 339 340 341 342
  }

  // Build the widget at index.
  Element _maybeGetElement(int index, BoxConstraints innerConstraints) {
    assert(index <= _childOffsets.length - 1);
    final Widget newWidget = _maybeBuildWidgetAt(index);
    if (newWidget == null)
343
      return null;
Adam Barth's avatar
Adam Barth committed
344
    return _inflateOrUpdateWidget(newWidget);
345 346
  }

347 348 349
  // Build the widget at index, handling the case where there is no such widget.
  // Update the offset for that widget.
  Element _getElementAtLastKnownOffset(int index, BoxConstraints innerConstraints) {
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    // Inflate the new widget; if there isn't one, abort early.
    assert(index == _childOffsets.length - 1);
    final Widget newWidget = _maybeBuildWidgetAt(index);
    if (newWidget == null)
      return null;
    final Element newElement = _inflateOrUpdateWidget(newWidget);

    // Update the offsets based on the newElement's dimensions.
    final double newExtent = _getElementExtent(newElement, innerConstraints);
    _childExtents.add(newExtent);
    _childOffsets.add(_childOffsets[index] + newExtent);
    assert(_childExtents.length == _childOffsets.length - 1);

    return newElement;
  }

  /// Returns the intrinsic size of the given element in the scroll direction
  double _getElementExtent(Element element, BoxConstraints innerConstraints) {
    final RenderBox childRenderObject = element.renderObject;
    switch (widget.direction) {
371
      case Axis.vertical:
372
        return childRenderObject.getMaxIntrinsicHeight(innerConstraints);
373
      case Axis.horizontal:
374
        return childRenderObject.getMaxIntrinsicWidth(innerConstraints);
375
    }
376
  }
377

378 379
  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    switch (widget.direction) {
380
      case Axis.vertical:
381
        return new BoxConstraints.tightFor(width: constraints.constrainWidth());
382
      case Axis.horizontal:
383 384
        return new BoxConstraints.tightFor(height: constraints.constrainHeight());
    }
385
  }
386

387 388 389 390 391 392 393 394
  /// This compares the offsets we had for an element with its current
  /// intrinsic dimensions.
  bool _debugIsSameSize(Element element, int index, BoxConstraints constraints) {
    assert(_invalidIndices.isEmpty);
    BoxConstraints innerConstraints = _getInnerConstraints(constraints);
    double newExtent = _getElementExtent(element, innerConstraints);
    bool result = _childExtents[index] == newExtent;
    if (!result)
395
      debugPrint("Element $element at index $index was size ${_childExtents[index]} but is now size $newExtent yet no invalidate() was received to that effect");
396
    return result;
397 398
  }

Adam Barth's avatar
Adam Barth committed
399
  double _getMaxExtent(BoxConstraints constraints) {
400
    switch (widget.direction) {
401
      case Axis.vertical:
Adam Barth's avatar
Adam Barth committed
402
        assert(constraints.maxHeight < double.INFINITY &&
403 404 405
          'There is no point putting a lazily-built vertical MixedViewport inside a box with infinite internal ' +
          'height (e.g. inside something else that scrolls vertically), because it would then just eagerly build ' +
          'all the children. You probably want to put the MixedViewport inside a Container with a fixed height.' is String);
Adam Barth's avatar
Adam Barth committed
406
        return constraints.maxHeight;
407
      case Axis.horizontal:
Adam Barth's avatar
Adam Barth committed
408
        assert(constraints.maxWidth < double.INFINITY &&
409 410 411
          'There is no point putting a lazily-built horizontal MixedViewport inside a box with infinite internal ' +
          'width (e.g. inside something else that scrolls horizontally), because it would then just eagerly build ' +
          'all the children. You probably want to put the MixedViewport inside a Container with a fixed width.' is String);
Adam Barth's avatar
Adam Barth committed
412
        return constraints.maxWidth;
413
    }
Adam Barth's avatar
Adam Barth committed
414 415 416 417 418 419 420 421 422 423
  }

  /// This is the core lazy-build algorithm. It builds widgets incrementally
  /// from index 0 until it has built enough widgets to cover itself, and
  /// discards any widgets that are not displayed.
  void _doLayout(BoxConstraints constraints) {
    final Map<_ChildKey, Element> newChildren = new Map<_ChildKey, Element>();
    final Map<int, Element> builtChildren = new Map<int, Element>();

    // Establish the start and end offsets based on our current constraints.
424
    final double endOffset = startOffset + _getMaxExtent(constraints);
425

426 427
    // Create the constraints that we will use to measure the children.
    final BoxConstraints innerConstraints = _getInnerConstraints(constraints);
428

429 430
    // Before doing the actual layout, fix the offsets for the widgets whose
    // size has apparently changed.
Adam Barth's avatar
Adam Barth committed
431
    if (!_isValid) {
432 433 434
      assert(_childOffsets.length > 0);
      assert(_childOffsets.length == _childExtents.length + 1);
      List<int> invalidIndices = _invalidIndices.toList();
435
      invalidIndices.sort();
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      for (int i = 0; i < invalidIndices.length; i += 1) {

        // Determine the indices for this pass.
        final int widgetIndex = invalidIndices[i];
        if (widgetIndex >= _childExtents.length)
          break; // we don't have that child, so there's nothing to invalidate
        int endIndex; // the last index into _childOffsets that we want to update this round
        if (i == invalidIndices.length - 1) {
          // This is the last invalid index. Update all the remaining entries in _childOffsets.
          endIndex = _childOffsets.length - 1;
        } else {
          endIndex = invalidIndices[i + 1];
          if (endIndex > _childOffsets.length - 1)
            endIndex = _childOffsets.length - 1; // no point updating beyond the last offset we know of
        }
        assert(widgetIndex >= 0);
        assert(endIndex < _childOffsets.length);
        assert(widgetIndex < endIndex);

        // Inflate the widget or update the existing element, as necessary.
        final Element newElement = _getElement(widgetIndex, innerConstraints);

        // Update the offsets based on the newElement's dimensions.
        _childExtents[widgetIndex] = _getElementExtent(newElement, innerConstraints);
        for (int j = widgetIndex + 1; j <= endIndex; j++)
          _childOffsets[j] = _childOffsets[j - 1] + _childExtents[j - 1];
        assert(_childOffsets.length == _childExtents.length + 1);

        // Decide if it's visible.
        final _ChildKey key = new _ChildKey.fromWidget(newElement.widget);
466
        final bool isVisible = _childOffsets[widgetIndex] < endOffset && _childOffsets[widgetIndex + 1] >= startOffset;
467
        if (isVisible) {
468 469 470
          // Keep it.
          newChildren[key] = newElement;
          builtChildren[widgetIndex] = newElement;
471
        } else {
472 473 474
          // Drop it.
          _childrenByKey.remove(key);
          updateChild(newElement, null, null);
475
        }
476

477
      }
478
      _invalidIndices.clear();
479 480
    }

481
    // Decide what the first child to render should be (startIndex), if any (haveChildren).
482 483
    int startIndex;
    bool haveChildren;
484 485 486
    if (endOffset < 0.0) {
      // We're so far scrolled up that nothing is visible.
      haveChildren = false;
487
    } else if (startOffset <= 0.0) {
488
      startIndex = 0;
489 490 491
      // If we're scrolled up past the top, then our first visible widget, if
      // any, is the first widget.
      if (_childExtents.length > 0) {
492 493
        haveChildren = true;
      } else {
494 495 496 497
        final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints);
        if (element != null) {
          newChildren[new _ChildKey.fromWidget(element.widget)] = element;
          builtChildren[startIndex] = element;
498 499 500
          haveChildren = true;
        } else {
          haveChildren = false;
501
          _didReachLastChild = true;
502 503 504
        }
      }
    } else {
505 506
      // We're at some sane (not higher than the top) scroll offset.
      // See if we can already find the offset in our cache.
507
      startIndex = _findIndexForOffsetBeforeOrAt(startOffset);
508 509 510 511
      if (startIndex < _childExtents.length) {
        // We already know of a child that would be visible at this offset.
        haveChildren = true;
      } else {
512
        // We don't have an offset on the list that is beyond the start offset.
513
        assert(_childOffsets.last <= startOffset);
514 515 516
        // Fill the list until this isn't true or until we know that the
        // list is complete (and thus we are overscrolled).
        while (true) {
517 518 519 520 521 522
          // Get the next element and cache its offset.
          final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints);
          if (element == null) {
            // Reached the end of the list. We are so far overscrolled, there's nothing to show.
            _didReachLastChild = true;
            haveChildren = false;
523 524
            break;
          }
525
          final _ChildKey key = new _ChildKey.fromWidget(element.widget);
526
          if (_childOffsets.last > startOffset) {
527 528 529 530
            // This element is visible! It must thus be our first visible child.
            newChildren[key] = element;
            builtChildren[startIndex] = element;
            haveChildren = true;
531 532
            break;
          }
533 534 535 536
          // This element is not visible. Drop the inflated element.
          // (We've already cached its offset for later use.)
          _childrenByKey.remove(key);
          updateChild(element, null, null);
537
          startIndex += 1;
538
          assert(startIndex == _childExtents.length);
539
        }
540
        assert(haveChildren == _childOffsets.last > startOffset);
541 542 543 544 545 546 547 548 549 550 551 552 553
        assert(() {
          if (haveChildren) {
            // We found a child to render. It's the last one for which we have an
            // offset in _childOffsets.
            // If we're here, we have at least one child, so our list has
            // at least two offsets, the top of the child and the bottom
            // of the child.
            assert(_childExtents.length >= 1);
            assert(_childOffsets.length == _childExtents.length + 1);
            assert(startIndex == _childExtents.length - 1);
          }
          return true;
        });
554 555 556
      }
    }
    assert(haveChildren != null);
557
    assert(haveChildren || _didReachLastChild || endOffset < 0.0);
558
    assert(startIndex >= 0);
559
    assert(!haveChildren || startIndex < _childExtents.length);
560

561
    // Build the other widgets that are visible.
Adam Barth's avatar
Adam Barth committed
562
    int index;
563
    if (haveChildren) {
564
      // Build all the widgets we still need.
Adam Barth's avatar
Adam Barth committed
565
      for (index = startIndex; _childOffsets[index] < endOffset; index += 1) {
566
        if (!builtChildren.containsKey(index)) {
567 568 569
          Element element = _maybeGetElement(index, innerConstraints);
          if (element == null) {
            _didReachLastChild = true;
570 571
            break;
          }
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
          if (index == _childExtents.length) {
            // Remember this element's offset.
            final double newExtent = _getElementExtent(element, innerConstraints);
            _childExtents.add(newExtent);
            _childOffsets.add(_childOffsets[index] + newExtent);
            assert(_childOffsets.length == _childExtents.length + 1);
          } else {
            // Verify that it hasn't changed size.
            // If this assertion fires, it means you didn't call "invalidate"
            // before changing the size of one of your items.
            assert(_debugIsSameSize(element, index, constraints));
          }
          // Remember the element for when we place the children.
          final _ChildKey key = new _ChildKey.fromWidget(element.widget);
          newChildren[key] = element;
          builtChildren[index] = element;
588 589 590 591 592 593
        }
        assert(builtChildren[index] != null);
      }
    }

    // Remove any old children.
594
    for (_ChildKey oldChildKey in _childrenByKey.keys) {
595
      if (!newChildren.containsKey(oldChildKey))
596
        updateChild(_childrenByKey[oldChildKey], null, null);
597 598 599
    }

    if (haveChildren) {
Adam Barth's avatar
Adam Barth committed
600
      assert(index != null);
601 602
      // Place all our children in our RenderObject.
      // All the children we are placing are in builtChildren and newChildren.
Ian Hickson's avatar
Ian Hickson committed
603
      Element previousChild;
604 605 606 607 608
      for (int i = startIndex; i < index; ++i) {
        final Element element = builtChildren[i];
        if (element.slot != previousChild)
          updateSlotForChild(element, previousChild);
        previousChild = element;
609 610 611
      }
    }

612
    // Update our internal state.
613
    _childrenByKey = newChildren;
614 615 616 617 618 619 620 621 622 623 624 625
    _firstVisibleChildIndex = startIndex;
  }

  void updateSlotForChild(Element element, dynamic newSlot) {
    assert(newSlot == null || newSlot == _omit || newSlot is Element);
    super.updateSlotForChild(element, newSlot);
  }

  void insertChildRenderObject(RenderObject child, dynamic slot) {
    if (slot == _omit)
      return;
    assert(slot == null || slot is Element);
626
    renderObject.insert(child, after: slot?.renderObject);
627 628 629 630 631 632
  }

  void moveChildRenderObject(RenderObject child, dynamic slot) {
    if (slot == _omit)
      return;
    assert(slot == null || slot is Element);
633 634
    RenderObject previousSibling = slot?.renderObject;
    assert(previousSibling == null || previousSibling.parent == renderObject);
635
    if (child.parent == renderObject)
636
      renderObject.move(child, after: previousSibling);
637
    else
638
      renderObject.insert(child, after: previousSibling);
639 640 641 642 643 644
  }

  void removeChildRenderObject(RenderObject child) {
    if (child.parent != renderObject)
      return; // probably had slot == _omit when inserted
    renderObject.remove(child);
645 646 647
  }

}