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

import 'dart:math' as math;

xster's avatar
xster committed
7
import 'package:flutter/foundation.dart';
8 9 10 11 12 13 14 15

import 'box.dart';
import 'object.dart';
import 'sliver.dart';
import 'sliver_multi_box_adaptor.dart';

/// Describes the placement of a child in a [RenderSliverGrid].
///
16 17 18 19 20 21 22 23 24 25
/// This class is similar to [Rect], in that it gives a two-dimensional position
/// and a two-dimensional dimension, but is direction-agnostic.
///
/// {@tool dartpad}
/// This example shows how a custom [SliverGridLayout] uses [SliverGridGeometry]
/// to lay out the children.
///
/// ** See code in examples/api/lib/widgets/scroll_view/grid_view.0.dart **
/// {@end-tool}
///
26 27
/// See also:
///
28 29 30
///  * [SliverGridLayout], which represents the geometry of all the tiles in a
///    grid.
///  * [SliverGridLayout.getGeometryForChildIndex], which returns this object
31 32 33
///    to describe the child's placement.
///  * [RenderSliverGrid], which uses this class during its
///    [RenderSliverGrid.performLayout] method.
34
@immutable
35 36 37
class SliverGridGeometry {
  /// Creates an object that describes the placement of a child in a [RenderSliverGrid].
  const SliverGridGeometry({
38 39 40 41
    required this.scrollOffset,
    required this.crossAxisOffset,
    required this.mainAxisExtent,
    required this.crossAxisExtent,
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  });

  /// The scroll offset of the leading edge of the child relative to the leading
  /// edge of the parent.
  final double scrollOffset;

  /// The offset of the child in the non-scrolling axis.
  ///
  /// If the scroll axis is vertical, this offset is from the left-most edge of
  /// the parent to the left-most edge of the child. If the scroll axis is
  /// horizontal, this offset is from the top-most edge of the parent to the
  /// top-most edge of the child.
  final double crossAxisOffset;

  /// The extent of the child in the scrolling axis.
  ///
  /// If the scroll axis is vertical, this extent is the child's height. If the
  /// scroll axis is horizontal, this extent is the child's width.
  final double mainAxisExtent;

  /// The extent of the child in the non-scrolling axis.
  ///
  /// If the scroll axis is vertical, this extent is the child's width. If the
  /// scroll axis is horizontal, this extent is the child's height.
  final double crossAxisExtent;

Adam Barth's avatar
Adam Barth committed
68 69 70 71
  /// The scroll offset of the trailing edge of the child relative to the
  /// leading edge of the parent.
  double get trailingScrollOffset => scrollOffset + mainAxisExtent;

72
  /// Returns a tight [BoxConstraints] that forces the child to have the
73
  /// required size, given a [SliverConstraints].
74 75 76 77 78 79 80
  BoxConstraints getBoxConstraints(SliverConstraints constraints) {
    return constraints.asBoxConstraints(
      minExtent: mainAxisExtent,
      maxExtent: mainAxisExtent,
      crossAxisExtent: crossAxisExtent,
    );
  }
Adam Barth's avatar
Adam Barth committed
81 82 83

  @override
  String toString() {
84 85 86 87 88 89 90
    final List<String> properties = <String>[
      'scrollOffset: $scrollOffset',
      'crossAxisOffset: $crossAxisOffset',
      'mainAxisExtent: $mainAxisExtent',
      'crossAxisExtent: $crossAxisExtent',
    ];
    return 'SliverGridGeometry(${properties.join(', ')})';
Adam Barth's avatar
Adam Barth committed
91
  }
92 93
}

94 95
/// The size and position of all the tiles in a [RenderSliverGrid].
///
96 97 98 99
/// Rather that providing a grid with a [SliverGridLayout] directly, the grid is
/// provided a [SliverGridDelegate], which computes a [SliverGridLayout] given a
/// set of [SliverConstraints]. This allows the algorithm to dynamically respond
/// to changes in the environment (e.g. the user rotating the device).
100 101
///
/// The tiles can be placed arbitrarily, but it is more efficient to place tiles
102 103 104 105 106 107 108 109 110 111
/// roughly in order by scroll offset because grids reify a contiguous sequence
/// of children.
///
/// {@tool dartpad}
/// This example shows how to construct a custom [SliverGridLayout] to lay tiles
/// in a grid form with some cells stretched to fit the entire width of the
/// grid (sometimes called "hero tiles").
///
/// ** See code in examples/api/lib/widgets/scroll_view/grid_view.0.dart **
/// {@end-tool}
112 113 114 115 116 117 118 119
///
/// See also:
///
///  * [SliverGridRegularTileLayout], which represents a layout that uses
///    equally sized and spaced tiles.
///  * [SliverGridGeometry], which represents the size and position of a single
///    tile in a grid.
///  * [SliverGridDelegate.getLayout], which returns this object to describe the
120
///    delegate's layout.
121 122
///  * [RenderSliverGrid], which uses this class during its
///    [RenderSliverGrid.performLayout] method.
123
@immutable
124 125 126 127 128
abstract class SliverGridLayout {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const SliverGridLayout();

129
  /// The minimum child index that intersects with (or is after) this scroll offset.
130 131
  int getMinChildIndexForScrollOffset(double scrollOffset);

132
  /// The maximum child index that intersects with (or is before) this scroll offset.
133 134 135 136 137
  int getMaxChildIndexForScrollOffset(double scrollOffset);

  /// The size and position of the child with the given index.
  SliverGridGeometry getGeometryForChildIndex(int index);

138 139 140 141 142
  /// The scroll extent needed to fully display all the tiles if there are
  /// `childCount` children in total.
  ///
  /// The child count will never be null.
  double computeMaxScrollOffset(int childCount);
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
}

/// A [SliverGridLayout] that uses equally sized and spaced tiles.
///
/// Rather that providing a grid with a [SliverGridLayout] directly, you instead
/// provide the grid a [SliverGridDelegate], which can compute a
/// [SliverGridLayout] given the current [SliverConstraints].
///
/// This layout is used by [SliverGridDelegateWithFixedCrossAxisCount] and
/// [SliverGridDelegateWithMaxCrossAxisExtent].
///
/// See also:
///
///  * [SliverGridDelegateWithFixedCrossAxisCount], which uses this layout.
///  * [SliverGridDelegateWithMaxCrossAxisExtent], which uses this layout.
158
///  * [SliverGridLayout], which represents an arbitrary tile layout.
159 160 161
///  * [SliverGridGeometry], which represents the size and position of a single
///    tile in a grid.
///  * [SliverGridDelegate.getLayout], which returns this object to describe the
162
///    delegate's layout.
163 164 165 166 167
///  * [RenderSliverGrid], which uses this class during its
///    [RenderSliverGrid.performLayout] method.
class SliverGridRegularTileLayout extends SliverGridLayout {
  /// Creates a layout that uses equally sized and spaced tiles.
  ///
168 169
  /// All of the arguments must not be negative. The `crossAxisCount` argument
  /// must be greater than zero.
170
  const SliverGridRegularTileLayout({
171 172 173 174 175 176
    required this.crossAxisCount,
    required this.mainAxisStride,
    required this.crossAxisStride,
    required this.childMainAxisExtent,
    required this.childCrossAxisExtent,
    required this.reverseCrossAxis,
177 178 179 180 181
  }) : assert(crossAxisCount > 0),
       assert(mainAxisStride >= 0),
       assert(crossAxisStride >= 0),
       assert(childMainAxisExtent >= 0),
       assert(childCrossAxisExtent >= 0);
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

  /// The number of children in the cross axis.
  final int crossAxisCount;

  /// The number of pixels from the leading edge of one tile to the leading edge
  /// of the next tile in the main axis.
  final double mainAxisStride;

  /// The number of pixels from the leading edge of one tile to the leading edge
  /// of the next tile in the cross axis.
  final double crossAxisStride;

  /// The number of pixels from the leading edge of one tile to the trailing
  /// edge of the same tile in the main axis.
  final double childMainAxisExtent;

  /// The number of pixels from the leading edge of one tile to the trailing
  /// edge of the same tile in the cross axis.
  final double childCrossAxisExtent;
201

202 203 204 205 206 207 208 209 210 211 212
  /// Whether the children should be placed in the opposite order of increasing
  /// coordinates in the cross axis.
  ///
  /// For example, if the cross axis is horizontal, the children are placed from
  /// left to right when [reverseCrossAxis] is false and from right to left when
  /// [reverseCrossAxis] is true.
  ///
  /// Typically set to the return value of [axisDirectionIsReversed] applied to
  /// the [SliverConstraints.crossAxisDirection].
  final bool reverseCrossAxis;

213
  @override
214
  int getMinChildIndexForScrollOffset(double scrollOffset) {
215
    return mainAxisStride > precisionErrorTolerance ? crossAxisCount * (scrollOffset ~/ mainAxisStride) : 0;
216 217 218 219
  }

  @override
  int getMaxChildIndexForScrollOffset(double scrollOffset) {
220 221 222 223 224
    if (mainAxisStride > 0.0) {
      final int mainAxisCount = (scrollOffset / mainAxisStride).ceil();
      return math.max(0, crossAxisCount * mainAxisCount - 1);
    }
    return 0;
225 226
  }

227
  double _getOffsetFromStartInCrossAxis(double crossAxisStart) {
228
    if (reverseCrossAxis) {
229
      return crossAxisCount * crossAxisStride - crossAxisStart - childCrossAxisExtent - (crossAxisStride - childCrossAxisExtent);
230
    }
231 232 233
    return crossAxisStart;
  }

234 235
  @override
  SliverGridGeometry getGeometryForChildIndex(int index) {
236
    final double crossAxisStart = (index % crossAxisCount) * crossAxisStride;
237
    return SliverGridGeometry(
238
      scrollOffset: (index ~/ crossAxisCount) * mainAxisStride,
239
      crossAxisOffset: _getOffsetFromStartInCrossAxis(crossAxisStart),
240 241 242 243 244 245
      mainAxisExtent: childMainAxisExtent,
      crossAxisExtent: childCrossAxisExtent,
    );
  }

  @override
246
  double computeMaxScrollOffset(int childCount) {
247 248 249 250 251
    if (childCount == 0) {
      // There are no children in the grid. The max scroll offset should be
      // zero.
      return 0.0;
    }
252
    final int mainAxisCount = ((childCount - 1) ~/ crossAxisCount) + 1;
253 254 255
    final double mainAxisSpacing = mainAxisStride - childMainAxisExtent;
    return mainAxisStride * mainAxisCount - mainAxisSpacing;
  }
256 257
}

258 259 260 261
/// Controls the layout of tiles in a grid.
///
/// Given the current constraints on the grid, a [SliverGridDelegate] computes
/// the layout for the tiles in the grid. The tiles can be placed arbitrarily,
262
/// but it is more efficient to place tiles roughly in order by scroll offset
263 264
/// because grids reify a contiguous sequence of children.
///
265 266 267 268 269 270 271
/// {@tool dartpad}
/// This example shows how a [SliverGridDelegate] returns a [SliverGridLayout]
/// configured based on the provided [SliverConstraints] in [getLayout].
///
/// ** See code in examples/api/lib/widgets/scroll_view/grid_view.0.dart **
/// {@end-tool}
///
272 273 274 275 276 277 278 279 280 281 282
/// See also:
///
///  * [SliverGridDelegateWithFixedCrossAxisCount], which creates a layout with
///    a fixed number of tiles in the cross axis.
///  * [SliverGridDelegateWithMaxCrossAxisExtent], which creates a layout with
///    tiles that have a maximum cross-axis extent.
///  * [GridView], which uses this delegate to control the layout of its tiles.
///  * [SliverGrid], which uses this delegate to control the layout of its
///    tiles.
///  * [RenderSliverGrid], which uses this delegate to control the layout of its
///    tiles.
283 284 285 286 287
abstract class SliverGridDelegate {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const SliverGridDelegate();

288 289
  /// Returns information about the size and position of the tiles in the grid.
  SliverGridLayout getLayout(SliverConstraints constraints);
290

291 292 293 294 295 296
  /// Override this method to return true when the children need to be
  /// laid out.
  ///
  /// This should compare the fields of the current delegate and the given
  /// `oldDelegate` and return true if the fields are such that the layout would
  /// be different.
297
  bool shouldRelayout(covariant SliverGridDelegate oldDelegate);
298 299
}

300 301 302 303 304 305 306 307
/// Creates grid layouts with a fixed number of tiles in the cross axis.
///
/// For example, if the grid is vertical, this delegate will create a layout
/// with a fixed number of columns. If the grid is horizontal, this delegate
/// will create a layout with a fixed number of rows.
///
/// This delegate creates grids with equally sized and spaced tiles.
///
308
/// {@tool dartpad}
309 310 311 312
/// Here is an example using the [childAspectRatio] property. On a device with a
/// screen width of 800.0, it creates a GridView with each tile with a width of
/// 200.0 and a height of 100.0.
///
313
/// ** See code in examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0.dart **
314 315
/// {@end-tool}
///
316
/// {@tool dartpad}
317 318 319 320
/// Here is an example using the [mainAxisExtent] property. On a device with a
/// screen width of 800.0, it creates a GridView with each tile with a width of
/// 200.0 and a height of 150.0.
///
321
/// ** See code in examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.1.dart **
322 323
/// {@end-tool}
///
324 325 326 327 328 329 330 331 332 333 334
/// See also:
///
///  * [SliverGridDelegateWithMaxCrossAxisExtent], which creates a layout with
///    tiles that have a maximum cross-axis extent.
///  * [SliverGridDelegate], which creates arbitrary layouts.
///  * [GridView], which can use this delegate to control the layout of its
///    tiles.
///  * [SliverGrid], which can use this delegate to control the layout of its
///    tiles.
///  * [RenderSliverGrid], which can use this delegate to control the layout of
///    its tiles.
335
class SliverGridDelegateWithFixedCrossAxisCount extends SliverGridDelegate {
336 337 338
  /// Creates a delegate that makes grid layouts with a fixed number of tiles in
  /// the cross axis.
  ///
339 340 341
  /// The `mainAxisSpacing`, `mainAxisExtent` and `crossAxisSpacing` arguments
  /// must not be negative. The `crossAxisCount` and `childAspectRatio`
  /// arguments must be greater than zero.
342
  const SliverGridDelegateWithFixedCrossAxisCount({
343
    required this.crossAxisCount,
344 345 346
    this.mainAxisSpacing = 0.0,
    this.crossAxisSpacing = 0.0,
    this.childAspectRatio = 1.0,
347
    this.mainAxisExtent,
348 349 350 351
  }) : assert(crossAxisCount > 0),
       assert(mainAxisSpacing >= 0),
       assert(crossAxisSpacing >= 0),
       assert(childAspectRatio > 0);
352 353 354 355 356 357 358 359 360 361 362 363 364

  /// The number of children in the cross axis.
  final int crossAxisCount;

  /// The number of logical pixels between each child along the main axis.
  final double mainAxisSpacing;

  /// The number of logical pixels between each child along the cross axis.
  final double crossAxisSpacing;

  /// The ratio of the cross-axis to the main-axis extent of each child.
  final double childAspectRatio;

365 366 367 368 369 370
  /// The extent of each tile in the main axis. If provided it would define the
  /// logical pixels taken by each tile in the main-axis.
  ///
  /// If null, [childAspectRatio] is used instead.
  final double? mainAxisExtent;

371 372 373 374 375 376 377 378 379
  bool _debugAssertIsValid() {
    assert(crossAxisCount > 0);
    assert(mainAxisSpacing >= 0.0);
    assert(crossAxisSpacing >= 0.0);
    assert(childAspectRatio > 0.0);
    return true;
  }

  @override
380
  SliverGridLayout getLayout(SliverConstraints constraints) {
381
    assert(_debugAssertIsValid());
382 383 384 385
    final double usableCrossAxisExtent = math.max(
      0.0,
      constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1),
    );
386
    final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
387
    final double childMainAxisExtent = mainAxisExtent ?? childCrossAxisExtent / childAspectRatio;
388
    return SliverGridRegularTileLayout(
389 390 391 392 393
      crossAxisCount: crossAxisCount,
      mainAxisStride: childMainAxisExtent + mainAxisSpacing,
      crossAxisStride: childCrossAxisExtent + crossAxisSpacing,
      childMainAxisExtent: childMainAxisExtent,
      childCrossAxisExtent: childCrossAxisExtent,
394
      reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
395 396 397 398 399 400 401 402
    );
  }

  @override
  bool shouldRelayout(SliverGridDelegateWithFixedCrossAxisCount oldDelegate) {
    return oldDelegate.crossAxisCount != crossAxisCount
        || oldDelegate.mainAxisSpacing != mainAxisSpacing
        || oldDelegate.crossAxisSpacing != crossAxisSpacing
403 404
        || oldDelegate.childAspectRatio != childAspectRatio
        || oldDelegate.mainAxisExtent != mainAxisExtent;
405 406 407
  }
}

408
/// Creates grid layouts with tiles that each have a maximum cross-axis extent.
409 410 411
///
/// This delegate will select a cross-axis extent for the tiles that is as
/// large as possible subject to the following conditions:
412
///
413 414
///  - The extent evenly divides the cross-axis extent of the grid.
///  - The extent is at most [maxCrossAxisExtent].
415
///
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
/// For example, if the grid is vertical, the grid is 500.0 pixels wide, and
/// [maxCrossAxisExtent] is 150.0, this delegate will create a grid with 4
/// columns that are 125.0 pixels wide.
///
/// This delegate creates grids with equally sized and spaced tiles.
///
/// See also:
///
///  * [SliverGridDelegateWithFixedCrossAxisCount], which creates a layout with
///    a fixed number of tiles in the cross axis.
///  * [SliverGridDelegate], which creates arbitrary layouts.
///  * [GridView], which can use this delegate to control the layout of its
///    tiles.
///  * [SliverGrid], which can use this delegate to control the layout of its
///    tiles.
///  * [RenderSliverGrid], which can use this delegate to control the layout of
///    its tiles.
433
class SliverGridDelegateWithMaxCrossAxisExtent extends SliverGridDelegate {
434 435
  /// Creates a delegate that makes grid layouts with tiles that have a maximum
  /// cross-axis extent.
436
  ///
437 438
  /// The [maxCrossAxisExtent], [mainAxisExtent], [mainAxisSpacing],
  /// and [crossAxisSpacing] arguments must not be negative.
439
  /// The [childAspectRatio] argument must be greater than zero.
440
  const SliverGridDelegateWithMaxCrossAxisExtent({
441
    required this.maxCrossAxisExtent,
442 443 444
    this.mainAxisSpacing = 0.0,
    this.crossAxisSpacing = 0.0,
    this.childAspectRatio = 1.0,
445
    this.mainAxisExtent,
446 447 448 449
  }) : assert(maxCrossAxisExtent > 0),
       assert(mainAxisSpacing >= 0),
       assert(crossAxisSpacing >= 0),
       assert(childAspectRatio > 0);
450

451 452 453 454 455 456 457 458 459 460 461
  /// The maximum extent of tiles in the cross axis.
  ///
  /// This delegate will select a cross-axis extent for the tiles that is as
  /// large as possible subject to the following conditions:
  ///
  ///  - The extent evenly divides the cross-axis extent of the grid.
  ///  - The extent is at most [maxCrossAxisExtent].
  ///
  /// For example, if the grid is vertical, the grid is 500.0 pixels wide, and
  /// [maxCrossAxisExtent] is 150.0, this delegate will create a grid with 4
  /// columns that are 125.0 pixels wide.
462 463 464 465 466 467 468 469 470 471 472
  final double maxCrossAxisExtent;

  /// The number of logical pixels between each child along the main axis.
  final double mainAxisSpacing;

  /// The number of logical pixels between each child along the cross axis.
  final double crossAxisSpacing;

  /// The ratio of the cross-axis to the main-axis extent of each child.
  final double childAspectRatio;

473 474 475 476 477 478
  /// The extent of each tile in the main axis. If provided it would define the
  /// logical pixels taken by each tile in the main-axis.
  ///
  /// If null, [childAspectRatio] is used instead.
  final double? mainAxisExtent;

479 480
  bool _debugAssertIsValid(double crossAxisExtent) {
    assert(crossAxisExtent > 0.0);
481 482 483 484 485 486 487 488
    assert(maxCrossAxisExtent > 0.0);
    assert(mainAxisSpacing >= 0.0);
    assert(crossAxisSpacing >= 0.0);
    assert(childAspectRatio > 0.0);
    return true;
  }

  @override
489
  SliverGridLayout getLayout(SliverConstraints constraints) {
490
    assert(_debugAssertIsValid(constraints.crossAxisExtent));
491
    int crossAxisCount = (constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing)).ceil();
492 493 494
    // Ensure a minimum count of 1, can be zero and result in an infinite extent
    // below when the window size is 0.
    crossAxisCount = math.max(1, crossAxisCount);
495 496 497 498
    final double usableCrossAxisExtent = math.max(
      0.0,
      constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1),
    );
499
    final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
500
    final double childMainAxisExtent = mainAxisExtent ?? childCrossAxisExtent / childAspectRatio;
501
    return SliverGridRegularTileLayout(
502 503 504 505 506
      crossAxisCount: crossAxisCount,
      mainAxisStride: childMainAxisExtent + mainAxisSpacing,
      crossAxisStride: childCrossAxisExtent + crossAxisSpacing,
      childMainAxisExtent: childMainAxisExtent,
      childCrossAxisExtent: childCrossAxisExtent,
507
      reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
508 509 510 511 512 513 514 515
    );
  }

  @override
  bool shouldRelayout(SliverGridDelegateWithMaxCrossAxisExtent oldDelegate) {
    return oldDelegate.maxCrossAxisExtent != maxCrossAxisExtent
        || oldDelegate.mainAxisSpacing != mainAxisSpacing
        || oldDelegate.crossAxisSpacing != crossAxisSpacing
516 517
        || oldDelegate.childAspectRatio != childAspectRatio
        || oldDelegate.mainAxisExtent != mainAxisExtent;
518 519 520
  }
}

521
/// Parent data structure used by [RenderSliverGrid].
522
class SliverGridParentData extends SliverMultiBoxAdaptorParentData {
523 524 525 526 527 528
  /// The offset of the child in the non-scrolling axis.
  ///
  /// If the scroll axis is vertical, this offset is from the left-most edge of
  /// the parent to the left-most edge of the child. If the scroll axis is
  /// horizontal, this offset is from the top-most edge of the parent to the
  /// top-most edge of the child.
529
  double? crossAxisOffset;
530 531 532 533 534

  @override
  String toString() => 'crossAxisOffset=$crossAxisOffset; ${super.toString()}';
}

535
/// A sliver that places multiple box children in a two dimensional arrangement.
536 537 538 539 540 541 542 543 544 545 546
///
/// [RenderSliverGrid] places its children in arbitrary positions determined by
/// [gridDelegate]. Each child is forced to have the size specified by the
/// [gridDelegate].
///
/// See also:
///
///  * [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.
547
class RenderSliverGrid extends RenderSliverMultiBoxAdaptor {
548 549
  /// Creates a sliver that contains multiple box children that whose size and
  /// position are determined by a delegate.
550
  RenderSliverGrid({
551
    required super.childManager,
552
    required SliverGridDelegate gridDelegate,
553
  }) : _gridDelegate = gridDelegate;
554 555 556

  @override
  void setupParentData(RenderObject child) {
557
    if (child.parentData is! SliverGridParentData) {
558
      child.parentData = SliverGridParentData();
559
    }
560 561
  }

562
  /// The delegate that controls the size and position of the children.
563 564
  SliverGridDelegate get gridDelegate => _gridDelegate;
  SliverGridDelegate _gridDelegate;
565
  set gridDelegate(SliverGridDelegate value) {
566
    if (_gridDelegate == value) {
567
      return;
568
    }
569
    if (value.runtimeType != _gridDelegate.runtimeType ||
570
        value.shouldRelayout(_gridDelegate)) {
571
      markNeedsLayout();
572
    }
573
    _gridDelegate = value;
574 575 576 577
  }

  @override
  double childCrossAxisPosition(RenderBox child) {
578
    final SliverGridParentData childParentData = child.parentData! as SliverGridParentData;
579
    return childParentData.crossAxisOffset!;
580 581 582 583
  }

  @override
  void performLayout() {
584
    final SliverConstraints constraints = this.constraints;
585
    childManager.didStartLayout();
586 587
    childManager.setDidUnderflow(false);

588
    final double scrollOffset = constraints.scrollOffset + constraints.cacheOrigin;
589
    assert(scrollOffset >= 0.0);
590 591 592
    final double remainingExtent = constraints.remainingCacheExtent;
    assert(remainingExtent >= 0.0);
    final double targetEndScrollOffset = scrollOffset + remainingExtent;
593

594 595 596
    final SliverGridLayout layout = _gridDelegate.getLayout(constraints);

    final int firstIndex = layout.getMinChildIndexForScrollOffset(scrollOffset);
597
    final int? targetLastIndex = targetEndScrollOffset.isFinite ?
598
      layout.getMaxChildIndexForScrollOffset(targetEndScrollOffset) : null;
599
    if (firstChild != null) {
600 601
      final int leadingGarbage = _calculateLeadingGarbage(firstIndex);
      final int trailingGarbage = targetLastIndex != null ? _calculateTrailingGarbage(targetLastIndex) : 0;
602 603 604
      collectGarbage(leadingGarbage, trailingGarbage);
    } else {
      collectGarbage(0, 0);
605 606
    }

607
    final SliverGridGeometry firstChildGridGeometry = layout.getGeometryForChildIndex(firstIndex);
608 609

    if (firstChild == null) {
610 611 612
      if (!addInitialChild(index: firstIndex, layoutOffset: firstChildGridGeometry.scrollOffset)) {
        // There are either no children, or we are past the end of all our children.
        final double max = layout.computeMaxScrollOffset(childManager.childCount);
613
        geometry = SliverGeometry(
614 615 616
          scrollExtent: max,
          maxPaintExtent: max,
        );
617
        childManager.didFinishLayout();
618 619 620 621
        return;
      }
    }

622 623
    final double leadingScrollOffset = firstChildGridGeometry.scrollOffset;
    double trailingScrollOffset = firstChildGridGeometry.trailingScrollOffset;
624
    RenderBox? trailingChildWithLayout;
625
    bool reachedEnd = false;
626

627
    for (int index = indexOf(firstChild!) - 1; index >= firstIndex; --index) {
628
      final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index);
629
      final RenderBox child = insertAndLayoutLeadingChild(
Ian Hickson's avatar
Ian Hickson committed
630
        gridGeometry.getBoxConstraints(constraints),
631
      )!;
632
      final SliverGridParentData childParentData = child.parentData! as SliverGridParentData;
633
      childParentData.layoutOffset = gridGeometry.scrollOffset;
634 635 636
      childParentData.crossAxisOffset = gridGeometry.crossAxisOffset;
      assert(childParentData.index == index);
      trailingChildWithLayout ??= child;
Adam Barth's avatar
Adam Barth committed
637
      trailingScrollOffset = math.max(trailingScrollOffset, gridGeometry.trailingScrollOffset);
638 639 640
    }

    if (trailingChildWithLayout == null) {
641
      firstChild!.layout(firstChildGridGeometry.getBoxConstraints(constraints));
642
      final SliverGridParentData childParentData = firstChild!.parentData! as SliverGridParentData;
643
      childParentData.layoutOffset = firstChildGridGeometry.scrollOffset;
644 645 646 647
      childParentData.crossAxisOffset = firstChildGridGeometry.crossAxisOffset;
      trailingChildWithLayout = firstChild;
    }

648
    for (int index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
649 650
      final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index);
      final BoxConstraints childConstraints = gridGeometry.getBoxConstraints(constraints);
651
      RenderBox? child = childAfter(trailingChildWithLayout!);
652
      if (child == null || indexOf(child) != index) {
653 654
        child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout);
        if (child == null) {
655
          reachedEnd = true;
656 657 658 659 660 661 662
          // We have run out of children.
          break;
        }
      } else {
        child.layout(childConstraints);
      }
      trailingChildWithLayout = child;
663
      final SliverGridParentData childParentData = child.parentData! as SliverGridParentData;
664
      childParentData.layoutOffset = gridGeometry.scrollOffset;
665 666
      childParentData.crossAxisOffset = gridGeometry.crossAxisOffset;
      assert(childParentData.index == index);
Adam Barth's avatar
Adam Barth committed
667
      trailingScrollOffset = math.max(trailingScrollOffset, gridGeometry.trailingScrollOffset);
668 669
    }

670
    final int lastIndex = indexOf(lastChild!);
671 672

    assert(debugAssertChildListIsNonEmptyAndContiguous());
673
    assert(indexOf(firstChild!) == firstIndex);
674
    assert(targetLastIndex == null || lastIndex <= targetLastIndex);
675

676 677 678 679 680 681 682 683 684
    final double estimatedTotalExtent = reachedEnd
      ? trailingScrollOffset
      : childManager.estimateMaxScrollOffset(
          constraints,
          firstIndex: firstIndex,
          lastIndex: lastIndex,
          leadingScrollOffset: leadingScrollOffset,
          trailingScrollOffset: trailingScrollOffset,
        );
Adam Barth's avatar
Adam Barth committed
685
    final double paintExtent = calculatePaintOffset(
686
      constraints,
687
      from: math.min(constraints.scrollOffset, leadingScrollOffset),
688 689
      to: trailingScrollOffset,
    );
690 691 692 693 694
    final double cacheExtent = calculateCacheOffset(
      constraints,
      from: leadingScrollOffset,
      to: trailingScrollOffset,
    );
695

696
    geometry = SliverGeometry(
697
      scrollExtent: estimatedTotalExtent,
Adam Barth's avatar
Adam Barth committed
698
      paintExtent: paintExtent,
699
      maxPaintExtent: estimatedTotalExtent,
700
      cacheExtent: cacheExtent,
701
      hasVisualOverflow: estimatedTotalExtent > paintExtent || constraints.scrollOffset > 0.0 || constraints.overlap != 0.0,
702 703
    );

704 705
    // We may have started the layout while scrolled to the end, which
    // would not expose a new child.
706
    if (estimatedTotalExtent == trailingScrollOffset) {
707
      childManager.setDidUnderflow(true);
708
    }
709
    childManager.didFinishLayout();
710
  }
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

  int _calculateLeadingGarbage(int firstIndex) {
    RenderBox? walker = firstChild;
    int leadingGarbage = 0;
    while (walker != null && indexOf(walker) < firstIndex) {
      leadingGarbage += 1;
      walker = childAfter(walker);
    }
    return leadingGarbage;
  }

  int _calculateTrailingGarbage(int targetLastIndex) {
    RenderBox? walker = lastChild;
    int trailingGarbage = 0;
    while (walker != null && indexOf(walker) > targetLastIndex) {
      trailingGarbage += 1;
      walker = childBefore(walker);
    }
    return trailingGarbage;
  }
731
}