sliver.dart 33.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1 2 3 4 5 6 7 8 9
// Copyright 2016 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.

import 'dart:collection' show SplayTreeMap, HashMap;

import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';

10
import 'automatic_keep_alive.dart';
Ian Hickson's avatar
Ian Hickson committed
11
import 'basic.dart';
12
import 'framework.dart';
13

14 15 16 17 18
export 'package:flutter/rendering.dart' show
  SliverGridDelegate,
  SliverGridDelegateWithFixedCrossAxisCount,
  SliverGridDelegateWithMaxCrossAxisExtent;

19 20 21 22 23 24 25 26 27
/// A delegate that supplies children for slivers.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. Rather than receiving
/// their children as an explicit [List], they receive their children using a
/// [SliverChildDelegate].
///
/// It's uncommon to subclass [SliverChildDelegate]. Instead, consider using one
/// of the existing subclasses that provide adaptors to builder callbacks or
28
/// explicit child lists.
29 30 31 32 33 34 35
///
/// See also:
///
///  * [SliverChildBuilderDelegate], which is a delegate that uses a builder
///    callback to construct the children.
///  * [SliverChildListDelegate], which is a delegate that has an explicit list
///    of children.
Adam Barth's avatar
Adam Barth committed
36
abstract class SliverChildDelegate {
Ian Hickson's avatar
Ian Hickson committed
37 38
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
Adam Barth's avatar
Adam Barth committed
39
  const SliverChildDelegate();
Ian Hickson's avatar
Ian Hickson committed
40

41 42 43 44 45 46
  /// Returns the child with the given index.
  ///
  /// Should return null if asked to build a widget with a greater index than
  /// exists.
  ///
  /// Subclasses typically override this function and wrap their children in
47
  /// [AutomaticKeepAlive] and [RepaintBoundary] widgets.
Ian Hickson's avatar
Ian Hickson committed
48 49
  Widget build(BuildContext context, int index);

50 51 52 53 54 55 56 57
  /// Returns an estimate of the number of children this delegate will build.
  ///
  /// Used to estimate the maximum scroll offset if [estimateMaxScrollOffset]
  /// returns null.
  ///
  /// Return null if there are an unbounded number of children or if it would
  /// be too difficult to estimate the number of children.
  int get estimatedChildCount => null;
Ian Hickson's avatar
Ian Hickson committed
58

59 60 61 62 63 64 65
  /// Returns an estimate of the max scroll extent for all the children.
  ///
  /// Subclasses should override this function if they have additional
  /// information about their max scroll extent.
  ///
  /// The default implementation returns null, which causes the caller to
  /// extrapolate the max scroll offset from the given parameters.
66
  double estimateMaxScrollOffset(
Ian Hickson's avatar
Ian Hickson committed
67 68 69 70
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
71 72
  ) => null;

73 74 75 76 77 78 79 80 81 82
  /// Called at the end of layout to indicate that layout is now complete.
  ///
  /// The `firstIndex` argument is the index of the first child that was
  /// included in the current layout. The `lastIndex` argument is the index of
  /// the last child that was included in the current layout.
  ///
  /// Useful for subclasses that which to track which children are included in
  /// the underlying render tree.
  void didFinishLayout(int firstIndex, int lastIndex) {}

83 84 85 86 87 88 89 90 91
  /// Called whenever a new instance of the child delegate class is
  /// provided to the sliver.
  ///
  /// If the new instance represents different information than the old
  /// instance, then the method should return true, otherwise it should return
  /// false.
  ///
  /// If the method returns false, then the [build] call might be optimized
  /// away.
92
  bool shouldRebuild(covariant SliverChildDelegate oldDelegate);
93 94 95

  @override
  String toString() {
96
    final List<String> description = <String>[];
97
    debugFillDescription(description);
98
    return '${describeIdentity(this)}(${description.join(", ")})';
99 100
  }

101
  /// Add additional information to the given description for use by [toString].
102
  @protected
103
  @mustCallSuper
104 105 106 107 108 109 110 111 112
  void debugFillDescription(List<String> description) {
    try {
      final int children = estimatedChildCount;
      if (children != null)
        description.add('estimated child count: $children');
    } catch (e) {
      description.add('estimated child count: EXCEPTION (${e.runtimeType})');
    }
  }
Ian Hickson's avatar
Ian Hickson committed
113 114
}

115 116 117 118
/// A delegate that supplies children for slivers using a builder callback.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. This delegate provides
119 120 121 122
/// children using an [IndexedWidgetBuilder] callback, so that the children do
/// not even have to be built until they are displayed.
///
/// The widgets returned from the builder callback are automatically wrapped in
123 124 125
/// [AutomaticKeepAlive] widgets if [addAutomaticKeepAlives] is true (the
/// default) and in [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
126 127 128 129 130
///
/// See also:
///
///  * [SliverChildListDelegate], which is a delegate that has an explicit list
///    of children.
131
class SliverChildBuilderDelegate extends SliverChildDelegate {
132
  /// Creates a delegate that supplies children for slivers using the given
133 134
  /// builder callback.
  ///
135 136
  /// The [builder], [addAutomaticKeepAlives], and [addRepaintBoundaries]
  /// arguments must not be null.
137 138 139
  const SliverChildBuilderDelegate(
    this.builder, {
    this.childCount,
140
    this.addAutomaticKeepAlives: true,
141 142
    this.addRepaintBoundaries: true,
  }) : assert(builder != null),
143
       assert(addAutomaticKeepAlives != null),
144
       assert(addRepaintBoundaries != null);
145

146 147 148 149 150 151 152 153 154 155
  /// Called to build children for the sliver.
  ///
  /// Will be called only for indices greater than or equal to zero and less
  /// than [childCount] (if [childCount] is non-null).
  ///
  /// Should return null if asked to build a widget with a greater index than
  /// exists.
  ///
  /// The delegate wraps the children returned by this builder in
  /// [RepaintBoundary] widgets.
156 157
  final IndexedWidgetBuilder builder;

158 159 160 161
  /// The total number of children this delegate can provide.
  ///
  /// If null, the number of children is determined by the least index for which
  /// [builder] returns null.
162 163
  final int childCount;

164 165 166 167 168 169 170 171 172 173 174 175 176 177
  /// Whether to wrap each child in an [AutomaticKeepAlive].
  ///
  /// Typically, children in lazy list are wrapped in [AutomaticKeepAlive]
  /// widgets so that children can use [KeepAliveNotification]s to preserve
  /// their state when they would otherwise be garbage collected off-screen.
  ///
  /// This feature (and [addRepaintBoundaries]) must be disabled if the children
  /// are going to manually maintain their [KeepAlive] state. It may also be
  /// more efficient to disable this feature if it is known ahead of time that
  /// none of the children will ever try to keep themselves alive.
  ///
  /// Defaults to true.
  final bool addAutomaticKeepAlives;

178 179 180 181 182 183 184 185 186 187 188
  /// Whether to wrap each child in a [RepaintBoundary].
  ///
  /// Typically, children in a scrolling container are wrapped in repaint
  /// boundaries so that they do not need to be repainted as the list scrolls.
  /// If the children are easy to repaint (e.g., solid color blocks or a short
  /// snippet of text), it might be more efficient to not add a repaint boundary
  /// and simply repaint the children during scrolling.
  ///
  /// Defaults to true.
  final bool addRepaintBoundaries;

189 190 191 192 193
  @override
  Widget build(BuildContext context, int index) {
    assert(builder != null);
    if (index < 0 || (childCount != null && index >= childCount))
      return null;
194
    Widget child = builder(context, index);
195 196
    if (child == null)
      return null;
197 198 199 200 201
    if (addRepaintBoundaries)
      child = new RepaintBoundary.wrap(child, index);
    if (addAutomaticKeepAlives)
      child = new AutomaticKeepAlive(child: child);
    return child;
202 203 204 205 206 207
  }

  @override
  int get estimatedChildCount => childCount;

  @override
208
  bool shouldRebuild(covariant SliverChildBuilderDelegate oldDelegate) => true;
209 210
}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
/// A delegate that supplies children for slivers using an explicit list.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. This delegate provides
/// children using an explicit list, which is convenient but reduces the benefit
/// of building children lazily.
///
/// In general building all the widgets in advance is not efficient. It is
/// better to create a delegate that builds them on demand using
/// [SliverChildBuilderDelegate] or by subclassing [SliverChildDelegate]
/// directly.
///
/// This class is provided for the cases where either the list of children is
/// known well in advance (ideally the children are themselves compile-time
/// constants, for example), and therefore will not be built each time the
/// delegate itself is created, or the list is small, such that it's likely
/// always visible (and thus there is nothing to be gained by building it on
/// demand). For example, the body of a dialog box might fit both of these
/// conditions.
///
231
/// The widgets in the given [children] list are automatically wrapped in
232 233 234
/// [AutomaticKeepAlive] widgets if [addAutomaticKeepAlives] is true (the
/// default) and in [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
235
///
236 237 238 239
/// See also:
///
///  * [SliverChildBuilderDelegate], which is a delegate that uses a builder
///    callback to construct the children.
Adam Barth's avatar
Adam Barth committed
240
class SliverChildListDelegate extends SliverChildDelegate {
241 242
  /// Creates a delegate that supplies children for slivers using the given
  /// list.
243
  ///
244 245
  /// The [children], [addAutomaticKeepAlives], and [addRepaintBoundaries]
  /// arguments must not be null.
246 247
  const SliverChildListDelegate(
    this.children, {
248
    this.addAutomaticKeepAlives: true,
249 250
    this.addRepaintBoundaries: true,
  }) : assert(children != null),
251
       assert(addAutomaticKeepAlives != null),
252
       assert(addRepaintBoundaries != null);
Ian Hickson's avatar
Ian Hickson committed
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267
  /// Whether to wrap each child in an [AutomaticKeepAlive].
  ///
  /// Typically, children in lazy list are wrapped in [AutomaticKeepAlive]
  /// widgets so that children can use [KeepAliveNotification]s to preserve
  /// their state when they would otherwise be garbage collected off-screen.
  ///
  /// This feature (and [addRepaintBoundaries]) must be disabled if the children
  /// are going to manually maintain their [KeepAlive] state. It may also be
  /// more efficient to disable this feature if it is known ahead of time that
  /// none of the children will ever try to keep themselves alive.
  ///
  /// Defaults to true.
  final bool addAutomaticKeepAlives;

268 269 270 271 272 273 274 275 276 277 278 279
  /// Whether to wrap each child in a [RepaintBoundary].
  ///
  /// Typically, children in a scrolling container are wrapped in repaint
  /// boundaries so that they do not need to be repainted as the list scrolls.
  /// If the children are easy to repaint (e.g., solid color blocks or a short
  /// snippet of text), it might be more efficient to not add a repaint boundary
  /// and simply repaint the children during scrolling.
  ///
  /// Defaults to true.
  final bool addRepaintBoundaries;

  /// The widgets to display.
Ian Hickson's avatar
Ian Hickson committed
280 281 282 283 284 285 286
  final List<Widget> children;

  @override
  Widget build(BuildContext context, int index) {
    assert(children != null);
    if (index < 0 || index >= children.length)
      return null;
287
    Widget child = children[index];
288
    assert(child != null);
289 290 291 292 293
    if (addRepaintBoundaries)
      child = new RepaintBoundary.wrap(child, index);
    if (addAutomaticKeepAlives)
      child = new AutomaticKeepAlive(child: child);
    return child;
Ian Hickson's avatar
Ian Hickson committed
294 295
  }

296 297 298
  @override
  int get estimatedChildCount => children.length;

Ian Hickson's avatar
Ian Hickson committed
299
  @override
300
  bool shouldRebuild(covariant SliverChildListDelegate oldDelegate) {
Ian Hickson's avatar
Ian Hickson committed
301 302 303 304
    return children != oldDelegate.children;
  }
}

305 306 307
/// A base class for sliver that have multiple box children.
///
/// Helps subclasses build their children lazily using a [SliverChildDelegate].
Adam Barth's avatar
Adam Barth committed
308
abstract class SliverMultiBoxAdaptorWidget extends RenderObjectWidget {
309
  /// Initializes fields for subclasses.
310
  const SliverMultiBoxAdaptorWidget({
Ian Hickson's avatar
Ian Hickson committed
311 312
    Key key,
    @required this.delegate,
313 314
  }) : assert(delegate != null),
       super(key: key);
Ian Hickson's avatar
Ian Hickson committed
315

316 317 318 319 320 321 322 323 324 325
  /// The delegate that provides the children for this widget.
  ///
  /// The children are constructed lazily using this widget to avoid creating
  /// more children than are visible through the [Viewport].
  ///
  /// See also:
  ///
  ///  * [SliverChildBuilderDelegate] and [SliverChildListDelegate], which are
  ///    commonly used subclasses of [SliverChildDelegate] that use a builder
  ///    callback and an explicit child list, respectively.
Adam Barth's avatar
Adam Barth committed
326
  final SliverChildDelegate delegate;
Ian Hickson's avatar
Ian Hickson committed
327 328

  @override
Adam Barth's avatar
Adam Barth committed
329
  SliverMultiBoxAdaptorElement createElement() => new SliverMultiBoxAdaptorElement(this);
Ian Hickson's avatar
Ian Hickson committed
330 331

  @override
Adam Barth's avatar
Adam Barth committed
332
  RenderSliverMultiBoxAdaptor createRenderObject(BuildContext context);
Ian Hickson's avatar
Ian Hickson committed
333

334 335 336 337 338 339 340
  /// Returns an estimate of the max scroll extent for all the children.
  ///
  /// Subclasses should override this function if they have additional
  /// information about their max scroll extent.
  ///
  /// The default implementation returns calls
  /// [SliverChildDelegate.estimateMaxScrollOffset].
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  double estimateMaxScrollOffset(
    SliverConstraints constraints,
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
  ) {
    assert(lastIndex >= firstIndex);
    return delegate.estimateMaxScrollOffset(
      firstIndex,
      lastIndex,
      leadingScrollOffset,
      trailingScrollOffset,
    );
  }

Ian Hickson's avatar
Ian Hickson committed
357
  @override
358
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
359 360
    super.debugFillProperties(description);
    description.add(new DiagnosticsProperty<SliverChildDelegate>('delegate', delegate));
Ian Hickson's avatar
Ian Hickson committed
361 362 363
  }
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
/// A sliver that places multiple box children in a linear array along the main
/// axis.
///
/// Each child is forced to have the [SliverConstraints.crossAxisExtent] in the
/// cross axis but determines its own main axis extent.
///
/// [SliverList] determines its scroll offset by "dead reckoning" because
/// children outside the visible part of the sliver are not materialized, which
/// means [SliverList] cannot learn their main axis extent. Instead, newly
/// materialized children are placed adjacent to existing children.
///
/// If the children have a fixed extent in the main axis, consider using
/// [SliverFixedExtentList] rather than [SliverList] because
/// [SliverFixedExtentList] does not need to perform layout on its children to
/// obtain their extent in the main axis and is therefore more efficient.
///
/// See also:
///
///  * [SliverFixedExtentList], which is more efficient for children with
///    the same extent in the main axis.
384
///  * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList]
385
///    except that it uses a prototype list item instead of a pixel value to define
386
///    the main axis extent of each item.
387
///  * [SliverGrid], which places its children in arbitrary positions.
388
class SliverList extends SliverMultiBoxAdaptorWidget {
389
  /// Creates a sliver that places box children in a linear array.
390
  const SliverList({
Adam Barth's avatar
Adam Barth committed
391 392 393
    Key key,
    @required SliverChildDelegate delegate,
  }) : super(key: key, delegate: delegate);
Ian Hickson's avatar
Ian Hickson committed
394 395

  @override
396
  RenderSliverList createRenderObject(BuildContext context) {
Adam Barth's avatar
Adam Barth committed
397
    final SliverMultiBoxAdaptorElement element = context;
398
    return new RenderSliverList(childManager: element);
Adam Barth's avatar
Adam Barth committed
399 400
  }
}
Ian Hickson's avatar
Ian Hickson committed
401

402 403 404 405 406 407 408 409 410 411 412 413
/// A sliver that places multiple box children with the same main axis extent in
/// a linear array.
///
/// [SliverFixedExtentList] places its children in a linear array along the main
/// axis starting at offset zero and without gaps. Each child is forced to have
/// the [itemExtent] in the main axis and the
/// [SliverConstraints.crossAxisExtent] in the cross axis.
///
/// [SliverFixedExtentList] is more efficient than [SliverList] because
/// [SliverFixedExtentList] does not need to perform layout on its children to
/// obtain their extent in the main axis.
///
414 415 416 417 418 419 420 421 422 423 424
/// ## Sample code
///
/// This example, which would be inserted into a [CustomScrollView.slivers]
/// list, shows an infinite number of items in varying shades of blue:
///
/// ```dart
/// new SliverFixedExtentList(
///   itemExtent: 50.0,
///   delegate: new SliverChildBuilderDelegate(
///     (BuildContext context, int index) {
///       return new Container(
425
///         alignment: Alignment.center,
426 427 428 429 430 431 432 433
///         color: Colors.lightBlue[100 * (index % 9)],
///         child: new Text('list item $index'),
///       );
///     },
///   ),
/// )
/// ```
///
434 435
/// See also:
///
436
///  * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList]
437
///    except that it uses a prototype list item instead of a pixel value to define
438
///    the main axis extent of each item.
439
///  * [SliverFillViewport], which determines the [itemExtent] based on
440 441 442
///    [SliverConstraints.viewportMainAxisExtent].
///  * [SliverList], which does not require its children to have the same
///    extent in the main axis.
443
class SliverFixedExtentList extends SliverMultiBoxAdaptorWidget {
444 445
  /// Creates a sliver that places box children with the same main axis extent
  /// in a linear array.
446
  const SliverFixedExtentList({
Adam Barth's avatar
Adam Barth committed
447 448 449 450 451
    Key key,
    @required SliverChildDelegate delegate,
    @required this.itemExtent,
  }) : super(key: key, delegate: delegate);

452
  /// The extent the children are forced to have in the main axis.
Adam Barth's avatar
Adam Barth committed
453
  final double itemExtent;
Ian Hickson's avatar
Ian Hickson committed
454 455

  @override
456
  RenderSliverFixedExtentList createRenderObject(BuildContext context) {
Adam Barth's avatar
Adam Barth committed
457
    final SliverMultiBoxAdaptorElement element = context;
458
    return new RenderSliverFixedExtentList(childManager: element, itemExtent: itemExtent);
Ian Hickson's avatar
Ian Hickson committed
459 460 461
  }

  @override
462
  void updateRenderObject(BuildContext context, RenderSliverFixedExtentList renderObject) {
Adam Barth's avatar
Adam Barth committed
463
    renderObject.itemExtent = itemExtent;
Ian Hickson's avatar
Ian Hickson committed
464
  }
Adam Barth's avatar
Adam Barth committed
465 466
}

467 468 469 470 471 472
/// A sliver that places multiple box children in a two dimensional arrangement.
///
/// [SliverGrid] places its children in arbitrary positions determined by
/// [gridDelegate]. Each child is forced to have the size specified by the
/// [gridDelegate].
///
473 474 475
/// The main axis direction of a grid is the direction in which it scrolls; the
/// cross axis direction is the orthogonal direction.
///
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
/// ## Sample code
///
/// This example, which would be inserted into a [CustomScrollView.slivers]
/// list, shows twenty boxes in a pretty teal grid:
///
/// ```dart
/// new SliverGrid(
///   gridDelegate: new SliverGridDelegateWithMaxCrossAxisExtent(
///     maxCrossAxisExtent: 200.0,
///     mainAxisSpacing: 10.0,
///     crossAxisSpacing: 10.0,
///     childAspectRatio: 4.0,
///   ),
///   delegate: new SliverChildBuilderDelegate(
///     (BuildContext context, int index) {
///       return new Container(
492
///         alignment: Alignment.center,
493 494 495 496 497 498 499 500 501
///         color: Colors.teal[100 * (index % 9)],
///         child: new Text('grid item $index'),
///       );
///     },
///     childCount: 20,
///   ),
/// )
/// ```
///
502 503 504 505 506
/// See also:
///
///  * [SliverList], which places its children in a linear array.
///  * [SliverFixedExtentList], which places its children in a linear
///    array with a fixed extent in the main axis.
507
///  * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList]
508
///    except that it uses a prototype list item instead of a pixel value to define
509
///    the main axis extent of each item.
510
class SliverGrid extends SliverMultiBoxAdaptorWidget {
511 512
  /// Creates a sliver that places multiple box children in a two dimensional
  /// arrangement.
513
  const SliverGrid({
514 515 516 517 518
    Key key,
    @required SliverChildDelegate delegate,
    @required this.gridDelegate,
  }) : super(key: key, delegate: delegate);

519 520 521 522 523
  /// Creates a sliver that places multiple box children in a two dimensional
  /// arrangement with a fixed number of tiles in the cross axis.
  ///
  /// Uses a [SliverGridDelegateWithFixedCrossAxisCount] as the [gridDelegate],
  /// and a [SliverChildListDelegate] as the [delegate].
524 525 526 527
  ///
  /// See also:
  ///
  ///  * [new GridView.count], the equivalent constructor for [GridView] widgets.
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  SliverGrid.count({
    Key key,
    @required int crossAxisCount,
    double mainAxisSpacing: 0.0,
    double crossAxisSpacing: 0.0,
    double childAspectRatio: 1.0,
    List<Widget> children: const <Widget>[],
  }) : gridDelegate = new SliverGridDelegateWithFixedCrossAxisCount(
         crossAxisCount: crossAxisCount,
         mainAxisSpacing: mainAxisSpacing,
         crossAxisSpacing: crossAxisSpacing,
         childAspectRatio: childAspectRatio,
       ),
       super(key: key, delegate: new SliverChildListDelegate(children));

  /// Creates a sliver that places multiple box children in a two dimensional
544
  /// arrangement with tiles that each have a maximum cross-axis extent.
545 546 547
  ///
  /// Uses a [SliverGridDelegateWithMaxCrossAxisExtent] as the [gridDelegate],
  /// and a [SliverChildListDelegate] as the [delegate].
548 549 550 551
  ///
  /// See also:
  ///
  ///  * [new GridView.extent], the equivalent constructor for [GridView] widgets.
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  SliverGrid.extent({
    Key key,
    @required double maxCrossAxisExtent,
    double mainAxisSpacing: 0.0,
    double crossAxisSpacing: 0.0,
    double childAspectRatio: 1.0,
    List<Widget> children: const <Widget>[],
  }) : gridDelegate = new SliverGridDelegateWithMaxCrossAxisExtent(
         maxCrossAxisExtent: maxCrossAxisExtent,
         mainAxisSpacing: mainAxisSpacing,
         crossAxisSpacing: crossAxisSpacing,
         childAspectRatio: childAspectRatio,
       ),
       super(key: key, delegate: new SliverChildListDelegate(children));

567
  /// The delegate that controls the size and position of the children.
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  final SliverGridDelegate gridDelegate;

  @override
  RenderSliverGrid createRenderObject(BuildContext context) {
    final SliverMultiBoxAdaptorElement element = context;
    return new RenderSliverGrid(childManager: element, gridDelegate: gridDelegate);
  }

  @override
  void updateRenderObject(BuildContext context, RenderSliverGrid renderObject) {
    renderObject.gridDelegate = gridDelegate;
  }

  @override
  double estimateMaxScrollOffset(
    SliverConstraints constraints,
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
  ) {
    return super.estimateMaxScrollOffset(
      constraints,
      firstIndex,
      lastIndex,
      leadingScrollOffset,
      trailingScrollOffset,
595
    ) ?? gridDelegate.getLayout(constraints).estimateMaxScrollOffset(delegate.estimatedChildCount);
596 597 598
  }
}

599 600
/// A sliver that contains a multiple box children that each fill the viewport.
///
601 602 603
/// [SliverFillViewport] places its children in a linear array along the main
/// axis. Each child is sized to fill the viewport, both in the main and cross
/// axis.
604 605 606
///
/// See also:
///
607 608
///  * [SliverFixedExtentList], which has a configurable
///    [SliverFixedExtentList.itemExtent].
609
///  * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList]
610
///    except that it uses a prototype list item instead of a pixel value to define
611
///    the main axis extent of each item.
612 613
///  * [SliverList], which does not require its children to have the same
///    extent in the main axis.
614
class SliverFillViewport extends SliverMultiBoxAdaptorWidget {
615
  /// Creates a sliver whose box children that each fill the viewport.
616
  const SliverFillViewport({
Adam Barth's avatar
Adam Barth committed
617 618
    Key key,
    @required SliverChildDelegate delegate,
619
    this.viewportFraction: 1.0,
620 621 622
  }) : assert(viewportFraction != null),
       assert(viewportFraction > 0.0),
       super(key: key, delegate: delegate);
623

624 625 626 627 628
  /// The fraction of the viewport that each child should fill in the main axis.
  ///
  /// If this fraction is less than 1.0, more than one child will be visible at
  /// once. If this fraction is greater than 1.0, each child will be larger than
  /// the viewport in the main axis.
629
  final double viewportFraction;
Adam Barth's avatar
Adam Barth committed
630 631

  @override
632
  RenderSliverFillViewport createRenderObject(BuildContext context) {
Adam Barth's avatar
Adam Barth committed
633
    final SliverMultiBoxAdaptorElement element = context;
634
    return new RenderSliverFillViewport(childManager: element, viewportFraction: viewportFraction);
635 636 637
  }

  @override
638
  void updateRenderObject(BuildContext context, RenderSliverFillViewport renderObject) {
639
    renderObject.viewportFraction = viewportFraction;
Adam Barth's avatar
Adam Barth committed
640 641 642
  }
}

643 644 645 646
/// An element that lazily builds children for a [SliverMultiBoxAdaptorWidget].
///
/// Implements [RenderSliverBoxChildManager], which lets this element manage
/// the children of subclasses of [RenderSliverMultiBoxAdaptor].
Adam Barth's avatar
Adam Barth committed
647
class SliverMultiBoxAdaptorElement extends RenderObjectElement implements RenderSliverBoxChildManager {
648
  /// Creates an element that lazily builds children for the given widget.
Adam Barth's avatar
Adam Barth committed
649 650 651 652
  SliverMultiBoxAdaptorElement(SliverMultiBoxAdaptorWidget widget) : super(widget);

  @override
  SliverMultiBoxAdaptorWidget get widget => super.widget;
Ian Hickson's avatar
Ian Hickson committed
653 654

  @override
Adam Barth's avatar
Adam Barth committed
655 656 657
  RenderSliverMultiBoxAdaptor get renderObject => super.renderObject;

  @override
658
  void update(covariant SliverMultiBoxAdaptorWidget newWidget) {
Adam Barth's avatar
Adam Barth committed
659
    final SliverMultiBoxAdaptorWidget oldWidget = widget;
Ian Hickson's avatar
Ian Hickson committed
660
    super.update(newWidget);
Adam Barth's avatar
Adam Barth committed
661 662
    final SliverChildDelegate newDelegate = newWidget.delegate;
    final SliverChildDelegate oldDelegate = oldWidget.delegate;
Ian Hickson's avatar
Ian Hickson committed
663 664 665 666 667
    if (newDelegate != oldDelegate &&
        (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRebuild(oldDelegate)))
      performRebuild();
  }

668 669 670 671 672 673 674
  // We inflate widgets at two different times:
  //  1. When we ourselves are told to rebuild (see performRebuild).
  //  2. When our render object needs a new child (see createChild).
  // In both cases, we cache the results of calling into our delegate to get the widget,
  // so that if we do case 2 later, we don't call the builder again.
  // Any time we do case 1, though, we reset the cache.

675
  final Map<int, Widget> _childWidgets = new HashMap<int, Widget>();
676
  final SplayTreeMap<int, Element> _childElements = new SplayTreeMap<int, Element>();
Ian Hickson's avatar
Ian Hickson committed
677 678 679 680
  RenderBox _currentBeforeChild;

  @override
  void performRebuild() {
681
    _childWidgets.clear(); // Reset the cache, as described above.
Ian Hickson's avatar
Ian Hickson committed
682 683
    super.performRebuild();
    _currentBeforeChild = null;
Adam Barth's avatar
Adam Barth committed
684
    assert(_currentlyUpdatingChildIndex == null);
Ian Hickson's avatar
Ian Hickson committed
685
    try {
686 687 688 689 690 691 692 693 694
      int firstIndex = _childElements.firstKey();
      int lastIndex = _childElements.lastKey();
      if (_childElements.isEmpty) {
        firstIndex = 0;
        lastIndex = 0;
      } else if (_didUnderflow) {
        lastIndex += 1;
      }
      for (int index = firstIndex; index <= lastIndex; ++index) {
Adam Barth's avatar
Adam Barth committed
695
        _currentlyUpdatingChildIndex = index;
696
        final Element newChild = updateChild(_childElements[index], _build(index), index);
Ian Hickson's avatar
Ian Hickson committed
697 698 699 700 701 702 703 704
        if (newChild != null) {
          _childElements[index] = newChild;
          _currentBeforeChild = newChild.renderObject;
        } else {
          _childElements.remove(index);
        }
      }
    } finally {
Adam Barth's avatar
Adam Barth committed
705
      _currentlyUpdatingChildIndex = null;
Ian Hickson's avatar
Ian Hickson committed
706 707 708 709
    }
  }

  Widget _build(int index) {
710
    return _childWidgets.putIfAbsent(index, () => widget.delegate.build(this, index));
Ian Hickson's avatar
Ian Hickson committed
711 712
  }

Adam Barth's avatar
Adam Barth committed
713 714 715
  @override
  void createChild(int index, { @required RenderBox after }) {
    assert(_currentlyUpdatingChildIndex == null);
Ian Hickson's avatar
Ian Hickson committed
716
    owner.buildScope(this, () {
Adam Barth's avatar
Adam Barth committed
717
      final bool insertFirst = after == null;
Ian Hickson's avatar
Ian Hickson committed
718 719 720 721
      assert(insertFirst || _childElements[index-1] != null);
      _currentBeforeChild = insertFirst ? null : _childElements[index-1].renderObject;
      Element newChild;
      try {
Adam Barth's avatar
Adam Barth committed
722
        _currentlyUpdatingChildIndex = index;
Ian Hickson's avatar
Ian Hickson committed
723 724
        newChild = updateChild(_childElements[index], _build(index), index);
      } finally {
Adam Barth's avatar
Adam Barth committed
725
        _currentlyUpdatingChildIndex = null;
Ian Hickson's avatar
Ian Hickson committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
      }
      if (newChild != null) {
        _childElements[index] = newChild;
      } else {
        _childElements.remove(index);
      }
    });
  }

  @override
  void forgetChild(Element child) {
    assert(child != null);
    assert(child.slot != null);
    assert(_childElements.containsKey(child.slot));
    _childElements.remove(child.slot);
  }

Adam Barth's avatar
Adam Barth committed
743 744 745 746
  @override
  void removeChild(RenderBox child) {
    final int index = renderObject.indexOf(child);
    assert(_currentlyUpdatingChildIndex == null);
Ian Hickson's avatar
Ian Hickson committed
747 748 749 750
    assert(index >= 0);
    owner.buildScope(this, () {
      assert(_childElements.containsKey(index));
      try {
Adam Barth's avatar
Adam Barth committed
751 752
        _currentlyUpdatingChildIndex = index;
        final Element result = updateChild(_childElements[index], null, index);
Ian Hickson's avatar
Ian Hickson committed
753 754
        assert(result == null);
      } finally {
Adam Barth's avatar
Adam Barth committed
755
        _currentlyUpdatingChildIndex = null;
Ian Hickson's avatar
Ian Hickson committed
756 757 758 759 760 761
      }
      _childElements.remove(index);
      assert(!_childElements.containsKey(index));
    });
  }

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  double _extrapolateMaxScrollOffset(
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
  ) {
    final int childCount = widget.delegate.estimatedChildCount;
    if (childCount == null)
      return double.INFINITY;
    if (lastIndex == childCount - 1)
      return trailingScrollOffset;
    final int reifiedCount = lastIndex - firstIndex + 1;
    final double averageExtent = (trailingScrollOffset - leadingScrollOffset) / reifiedCount;
    final int remainingCount = childCount - lastIndex - 1;
    return trailingScrollOffset + averageExtent * remainingCount;
  }

Adam Barth's avatar
Adam Barth committed
779
  @override
780
  double estimateMaxScrollOffset(SliverConstraints constraints, {
Adam Barth's avatar
Adam Barth committed
781 782 783 784 785
    int firstIndex,
    int lastIndex,
    double leadingScrollOffset,
    double trailingScrollOffset,
  }) {
786 787 788 789 790 791 792
    return widget.estimateMaxScrollOffset(
      constraints,
      firstIndex,
      lastIndex,
      leadingScrollOffset,
      trailingScrollOffset,
    ) ?? _extrapolateMaxScrollOffset(
Adam Barth's avatar
Adam Barth committed
793 794 795
      firstIndex,
      lastIndex,
      leadingScrollOffset,
796
      trailingScrollOffset,
Adam Barth's avatar
Adam Barth committed
797 798 799
    );
  }

800 801 802 803 804 805 806 807 808 809 810 811 812
  @override
  void didStartLayout() {
    assert(debugAssertChildListLocked());
  }

  @override
  void didFinishLayout() {
    assert(debugAssertChildListLocked());
    final int firstIndex = _childElements.firstKey() ?? 0;
    final int lastIndex = _childElements.lastKey() ?? 0;
    widget.delegate.didFinishLayout(firstIndex, lastIndex);
  }

Adam Barth's avatar
Adam Barth committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
  int _currentlyUpdatingChildIndex;

  @override
  bool debugAssertChildListLocked() {
    assert(_currentlyUpdatingChildIndex == null);
    return true;
  }

  @override
  void didAdoptChild(RenderBox child) {
    assert(_currentlyUpdatingChildIndex != null);
    final SliverMultiBoxAdaptorParentData childParentData = child.parentData;
    childParentData.index = _currentlyUpdatingChildIndex;
  }

828 829 830 831 832 833 834
  bool _didUnderflow = false;

  @override
  void setDidUnderflow(bool value) {
    _didUnderflow = value;
  }

Ian Hickson's avatar
Ian Hickson committed
835
  @override
836
  void insertChildRenderObject(covariant RenderObject child, int slot) {
Adam Barth's avatar
Adam Barth committed
837 838
    assert(slot != null);
    assert(_currentlyUpdatingChildIndex == slot);
839
    assert(renderObject.debugValidateChild(child));
Ian Hickson's avatar
Ian Hickson committed
840 841
    renderObject.insert(child, after: _currentBeforeChild);
    assert(() {
842
      final SliverMultiBoxAdaptorParentData childParentData = child.parentData;
Ian Hickson's avatar
Ian Hickson committed
843 844
      assert(slot == childParentData.index);
      return true;
845
    }());
Ian Hickson's avatar
Ian Hickson committed
846 847 848
  }

  @override
849
  void moveChildRenderObject(covariant RenderObject child, int slot) {
Ian Hickson's avatar
Ian Hickson committed
850 851 852 853 854 855
    // TODO(ianh): At some point we should be better about noticing when a
    // particular LocalKey changes slot, and handle moving the nodes around.
    assert(false);
  }

  @override
856
  void removeChildRenderObject(covariant RenderObject child) {
Adam Barth's avatar
Adam Barth committed
857
    assert(_currentlyUpdatingChildIndex != null);
Ian Hickson's avatar
Ian Hickson committed
858 859 860 861 862 863 864 865 866 867 868
    renderObject.remove(child);
  }

  @override
  void visitChildren(ElementVisitor visitor) {
   // The toList() is to make a copy so that the underlying list can be modified by
   // the visitor:
   assert(!_childElements.values.any((Element child) => child == null));
    _childElements.values.toList().forEach(visitor);
  }
}
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

/// A sliver that contains a single box child that fills the remaining space in
/// the viewport.
///
/// [SliverFillRemaining] sizes its child to fill the viewport in the cross axis
/// and to fill the remaining space in the viewport in the main axis.
///
/// Typically this will be the last sliver in a viewport, since (by definition)
/// there is never any room for anything beyond this sliver.
///
/// See also:
///
///  * [SliverFillViewport], which sizes its children based on the
///    size of the viewport, regardless of what else is in the scroll view.
///  * [SliverList], which shows a list of variable-sized children in a
///    viewport.
class SliverFillRemaining extends SingleChildRenderObjectWidget {
886
  /// Creates a sliver that fills the remaining space in the viewport.
887
  const SliverFillRemaining({
888 889 890 891 892 893 894
    Key key,
    Widget child,
  }) : super(key: key, child: child);

  @override
  RenderSliverFillRemaining createRenderObject(BuildContext context) => new RenderSliverFillRemaining();
}
895 896 897 898 899 900 901 902 903 904

/// Mark a child as needing to stay alive even when it's in a lazy list that
/// would otherwise remove it.
///
/// This widget is for use in [SliverMultiBoxAdaptorWidget]s, such as
/// [SliverGrid] or [SliverList].
class KeepAlive extends ParentDataWidget<SliverMultiBoxAdaptorWidget> {
  /// Marks a child as needing to remain alive.
  ///
  /// The [child] and [keepAlive] arguments must not be null.
905
  const KeepAlive({
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    Key key,
    @required this.keepAlive,
    @required Widget child,
  }) : assert(child != null),
       assert(keepAlive != null),
       super(key: key, child: child);

  /// Whether to keep the child alive.
  ///
  /// If this is false, it is as if this widget was omitted.
  final bool keepAlive;

  @override
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is SliverMultiBoxAdaptorParentData);
    final SliverMultiBoxAdaptorParentData parentData = renderObject.parentData;
    if (parentData.keepAlive != keepAlive) {
      parentData.keepAlive = keepAlive;
      final AbstractNode targetParent = renderObject.parent;
925 926
      if (targetParent is RenderObject && !keepAlive)
        targetParent.markNeedsLayout(); // No need to redo layout if it became true.
927 928 929
    }
  }

930 931 932 933 934 935 936
  // We only return true if [keepAlive] is true, because turning _off_ keep
  // alive requires a layout to do the garbage collection (but turning it on
  // requires nothing, since by definition the widget is already alive and won't
  // go away _unless_ we do a layout).
  @override
  bool debugCanApplyOutOfTurn() => keepAlive;

937
  @override
938
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
939 940
    super.debugFillProperties(description);
    description.add(new DiagnosticsProperty<bool>('keepAlive', keepAlive));
941 942
  }
}