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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/material.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter_test/flutter_test.dart';
9

10 11
import 'semantics_tester.dart';

12
Future<void> test(WidgetTester tester, double offset, { double anchor = 0.0 }) {
13 14
  final ViewportOffset viewportOffset = ViewportOffset.fixed(offset);
  addTearDown(viewportOffset.dispose);
15
  return tester.pumpWidget(
16
    Directionality(
17
      textDirection: TextDirection.ltr,
18
      child: Viewport(
19
        anchor: anchor / 600.0,
20
        offset: viewportOffset,
21
        slivers: const <Widget>[
22 23 24 25 26
          SliverToBoxAdapter(child: SizedBox(height: 400.0)),
          SliverToBoxAdapter(child: SizedBox(height: 400.0)),
          SliverToBoxAdapter(child: SizedBox(height: 400.0)),
          SliverToBoxAdapter(child: SizedBox(height: 400.0)),
          SliverToBoxAdapter(child: SizedBox(height: 400.0)),
27 28 29 30
        ],
      ),
    ),
  );
31 32
}

33 34 35 36 37 38 39 40 41
Future<void> testSliverFixedExtentList(WidgetTester tester, List<String> items) {
  return tester.pumpWidget(
    Directionality(
      textDirection: TextDirection.ltr,
      child: CustomScrollView(
        slivers: <Widget>[
          SliverFixedExtentList(
            itemExtent: 900,
            delegate: SliverChildBuilderDelegate(
42
              (BuildContext context, int index) {
43 44 45 46
                return Center(
                  key: ValueKey<String>(items[index]),
                  child: KeepAlive(
                    items[index],
47
                  ),
48 49 50 51
                );
              },
              childCount : items.length,
              findChildIndexCallback: (Key key) {
52
                final ValueKey<String> valueKey = key as ValueKey<String>;
53
                return items.indexOf(valueKey.value);
54
              },
55 56 57 58 59 60 61 62
            ),
          ),
        ],
      ),
    ),
  );
}

63
void verify(WidgetTester tester, List<Offset> idealPositions, List<bool> idealVisibles) {
64
  final List<Offset> actualPositions = tester.renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)).map<Offset>(
65
    (RenderBox target) => target.localToGlobal(Offset.zero),
66
  ).toList();
67
  final List<bool> actualVisibles = tester.renderObjectList<RenderSliverToBoxAdapter>(find.byType(SliverToBoxAdapter, skipOffstage: false)).map<bool>(
68
    (RenderSliverToBoxAdapter target) => target.geometry!.visible,
69 70 71 72 73 74
  ).toList();
  expect(actualPositions, equals(idealPositions));
  expect(actualVisibles, equals(idealVisibles));
}

void main() {
75
  testWidgets('Viewport basic test', (WidgetTester tester) async {
76
    await test(tester, 0.0);
Adam Barth's avatar
Adam Barth committed
77
    expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0)));
78
    verify(tester, <Offset>[
79
      Offset.zero,
80
      const Offset(0.0, 400.0),
81 82 83
      const Offset(0.0, 800.0),
      const Offset(0.0, 1200.0),
      const Offset(0.0, 1600.0),
84 85 86
    ], <bool>[true, true, false, false, false]);

    await test(tester, 200.0);
87 88 89 90
    verify(tester, <Offset>[
      const Offset(0.0, -200.0),
      const Offset(0.0, 200.0),
      const Offset(0.0, 600.0),
91 92
      const Offset(0.0, 1000.0),
      const Offset(0.0, 1400.0),
93 94 95
    ], <bool>[true, true, false, false, false]);

    await test(tester, 600.0);
96 97 98 99 100
    verify(tester, <Offset>[
      const Offset(0.0, -600.0),
      const Offset(0.0, -200.0),
      const Offset(0.0, 200.0),
      const Offset(0.0, 600.0),
101
      const Offset(0.0, 1000.0),
102 103 104
    ], <bool>[false, true, true, false, false]);

    await test(tester, 900.0);
105 106 107 108 109
    verify(tester, <Offset>[
      const Offset(0.0, -900.0),
      const Offset(0.0, -500.0),
      const Offset(0.0, -100.0),
      const Offset(0.0, 300.0),
110
      const Offset(0.0, 700.0),
111 112 113
    ], <bool>[false, false, true, true, false]);
  });

114
  testWidgets('Viewport anchor test', (WidgetTester tester) async {
115
    await test(tester, 0.0, anchor: 100.0);
Adam Barth's avatar
Adam Barth committed
116
    expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0)));
117 118 119
    verify(tester, <Offset>[
      const Offset(0.0, 100.0),
      const Offset(0.0, 500.0),
120 121 122
      const Offset(0.0, 900.0),
      const Offset(0.0, 1300.0),
      const Offset(0.0, 1700.0),
123 124 125
    ], <bool>[true, true, false, false, false]);

    await test(tester, 200.0, anchor: 100.0);
126 127 128
    verify(tester, <Offset>[
      const Offset(0.0, -100.0),
      const Offset(0.0, 300.0),
129 130 131
      const Offset(0.0, 700.0),
      const Offset(0.0, 1100.0),
      const Offset(0.0, 1500.0),
132 133 134
    ], <bool>[true, true, false, false, false]);

    await test(tester, 600.0, anchor: 100.0);
135 136 137 138
    verify(tester, <Offset>[
      const Offset(0.0, -500.0),
      const Offset(0.0, -100.0),
      const Offset(0.0, 300.0),
139 140
      const Offset(0.0, 700.0),
      const Offset(0.0, 1100.0),
141 142 143
    ], <bool>[false, true, true, false, false]);

    await test(tester, 900.0, anchor: 100.0);
144 145 146
    verify(tester, <Offset>[
      const Offset(0.0, -800.0),
      const Offset(0.0, -400.0),
147
      Offset.zero,
148
      const Offset(0.0, 400.0),
149
      const Offset(0.0, 800.0),
150 151
    ], <bool>[false, false, true, true, false]);
  });
152

153
  testWidgets('Multiple grids and lists', (WidgetTester tester) async {
154
    await tester.pumpWidget(
155 156
      Center(
        child: SizedBox(
157 158
          width: 44.4,
          height: 60.0,
159
          child: Directionality(
160
            textDirection: TextDirection.ltr,
161
            child: CustomScrollView(
162
              slivers: <Widget>[
163 164
                SliverList(
                  delegate: SliverChildListDelegate(
165 166 167 168
                    const <Widget>[
                      SizedBox(height: 22.2, child: Text('TOP')),
                      SizedBox(height: 22.2),
                      SizedBox(height: 22.2),
169 170 171
                    ],
                  ),
                ),
172
                SliverFixedExtentList(
173
                  itemExtent: 22.2,
174
                  delegate: SliverChildListDelegate(
175 176 177 178
                    const <Widget>[
                      SizedBox(),
                      Text('A'),
                      SizedBox(),
179 180 181
                    ],
                  ),
                ),
182
                SliverGrid(
183 184 185
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                  ),
186
                  delegate: SliverChildListDelegate(
187 188 189 190
                    const <Widget>[
                      SizedBox(),
                      Text('B'),
                      SizedBox(),
191 192 193
                    ],
                  ),
                ),
194 195
                SliverList(
                  delegate: SliverChildListDelegate(
196 197 198 199
                    const <Widget>[
                      SizedBox(height: 22.2),
                      SizedBox(height: 22.2),
                      SizedBox(height: 22.2, child: Text('BOTTOM')),
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
    final TestGesture gesture = await tester.startGesture(const Offset(400.0, 300.0));
    expect(find.text('TOP'), findsOneWidget);
    expect(find.text('A'), findsNothing);
    expect(find.text('B'), findsNothing);
    expect(find.text('BOTTOM'), findsNothing);
    await gesture.moveBy(const Offset(0.0, -70.0));
    await tester.pump();
    expect(find.text('TOP'), findsNothing);
    expect(find.text('A'), findsOneWidget);
    expect(find.text('B'), findsNothing);
    expect(find.text('BOTTOM'), findsNothing);
    await gesture.moveBy(const Offset(0.0, -70.0));
    await tester.pump();
    expect(find.text('TOP'), findsNothing);
    expect(find.text('A'), findsNothing);
    expect(find.text('B'), findsOneWidget);
    expect(find.text('BOTTOM'), findsNothing);
    await gesture.moveBy(const Offset(0.0, -70.0));
    await tester.pump();
    expect(find.text('TOP'), findsNothing);
    expect(find.text('A'), findsNothing);
    expect(find.text('B'), findsNothing);
    expect(find.text('BOTTOM'), findsOneWidget);
  });
233

234
  testWidgets('Sliver grid can replace intermediate items', (WidgetTester tester) async {
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    // Regression test for https://github.com/flutter/flutter/issues/138749.
    // The bug happens when items in between first and last item changed while
    // the sliver layout only display a item in the middle of the list.
    final List<int> items = <int>[0, 1, 2, 3, 4, 5];
    final List<int> replacedItems = <int>[0, 2, 9, 10, 11, 12, 5];
    Future<void> pumpSliverGrid(bool replace) async {
      await tester.pumpWidget(
        Center(
          child: SizedBox(
            width: 200,
            height: 200,
            child: Directionality(
              textDirection: TextDirection.ltr,
              child: CustomScrollView(
                slivers: <Widget>[
                  SliverGrid(
                    gridDelegate: TestGridDelegate(replace),
                    delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                        final int item = replace
                            ? replacedItems[index]
                            : items[index];
                        return Container(
                          key: ValueKey<int>(item),
                          alignment: Alignment.center,
                          child: Text('item $item'),
                        );
                      },
                      childCount: replace ? 7 : 6,
                      findChildIndexCallback: (Key key) {
                        final int item = (key as ValueKey<int>).value;
                        final int index = replace
                            ? replacedItems.indexOf(item)
                            : items.indexOf(item);
                        return index >= 0 ? index : null;
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

    await pumpSliverGrid(false);
    expect(find.text('item 0'), findsOneWidget);
    expect(find.text('item 1'), findsOneWidget);
    expect(find.text('item 2'), findsOneWidget);
    expect(find.text('item 3'), findsOneWidget);
    expect(find.text('item 4'), findsOneWidget);

    await pumpSliverGrid(true);
    // The TestGridDelegate only show child at index 1 when not expand.
    expect(find.text('item 0'), findsNothing);
    expect(find.text('item 1'), findsNothing);
    expect(find.text('item 2'), findsOneWidget);
    expect(find.text('item 3'), findsNothing);
    expect(find.text('item 4'), findsNothing);
  });

297
  testWidgets('SliverFixedExtentList correctly clears garbage', (WidgetTester tester) async {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    final List<String> items = <String>['1', '2', '3', '4', '5', '6'];
    await testSliverFixedExtentList(tester, items);
    // Keep alive widgets require 1 frame to notify their parents. Pumps in between
    // drags to ensure widgets are kept alive.
    await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0));
    await tester.pump();
    await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0));
    await tester.pump();
    await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -800.0));
    await tester.pump();
    expect(find.text('1'), findsNothing);
    expect(find.text('2'), findsNothing);
    expect(find.text('3'), findsNothing);
    expect(find.text('4'), findsOneWidget);
    expect(find.text('5'), findsOneWidget);
    // Indexes [0, 1, 2] are kept alive and [3, 4] are in viewport, thus the sliver
    // will need to keep updating the elements at these indexes whenever a rebuild is
    // triggered. The current child list in RenderSliverFixedExtentList is
    // '4' -> '5' -> null.
    //
    // With the insertion below, all items will get shifted back 1 position. The sliver
    // will have to update indexes [0, 1, 2, 3, 4, 5]. Since this is the first time
    // item '0' gets initialized, mounting the element will cause it to attach to
    // child list in RenderSliverFixedExtentList. This will create a gap.
    // '0' -> '4' -> '5' -> null.
    items.insert(0, '0');
    await testSliverFixedExtentList(tester, items);
    // Sliver should collect leading and trailing garbage correctly.
    //
    // The child list update should occur in following order.
    // '0' -> '4' -> '5' -> null Started with Original list.
    // '4' -> null               Removed 1 leading garbage and 1 trailing garbage.
    // '3' -> '4' -> null        Prepended '3' because viewport is still at [3, 4].
    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsNothing);
    expect(find.text('2'), findsNothing);
    expect(find.text('3'), findsOneWidget);
    expect(find.text('4'), findsOneWidget);
  });

338
  testWidgets('SliverFixedExtentList handles underflow when its children changes', (WidgetTester tester) async {
339 340 341 342 343 344 345
    final List<String> items = <String>['1', '2', '3', '4', '5', '6'];
    final List<String> initializedChild = <String>[];
    List<Widget> children = <Widget>[];
    for (final String item in items) {
      children.add(
          StateInitSpy(
            item, () => initializedChild.add(item), key: ValueKey<String>(item),
346
          ),
347 348 349
      );
    }
    final ScrollController controller = ScrollController(initialScrollOffset: 5400);
350 351
    addTearDown(controller.dispose);

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: CustomScrollView(
          controller: controller,
          slivers: <Widget>[
            SliverFixedExtentList(
              itemExtent: 900,
              delegate: SliverChildListDelegate(children),
            ),
          ],
        ),
      ),
    );
    await tester.pumpAndSettle();
    expect(find.text('1'), findsNothing);
    expect(find.text('2'), findsNothing);
    expect(find.text('3'), findsNothing);
    expect(find.text('4'), findsNothing);
    expect(find.text('5'), findsNothing);
    expect(find.text('6'), findsOneWidget);
    expect(listEquals<String>(initializedChild, <String>['6']), isTrue);

    // move to item 1 and swap the children at the same time
    controller.jumpTo(0);
    final Widget temp = children[5];
    children[5] = children[0];
    children[0] = temp;
    children = List<Widget>.from(children);
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: CustomScrollView(
          controller: controller,
          slivers: <Widget>[
            SliverFixedExtentList(
              itemExtent: 900,
              delegate: SliverChildListDelegate(children),
            ),
          ],
        ),
      ),
    );
    expect(find.text('1'), findsNothing);
    expect(find.text('2'), findsNothing);
    expect(find.text('3'), findsNothing);
    expect(find.text('4'), findsNothing);
    expect(find.text('5'), findsNothing);
    expect(find.text('6'), findsOneWidget);
    // None of the children should be built.
    expect(listEquals<String>(initializedChild, <String>['6']), isTrue);
  });

405
  testWidgets(
406 407
    'SliverGrid Correctly layout children after rearranging',
    (WidgetTester tester) async {
408 409 410 411
      await tester.pumpWidget(const TestSliverGrid(
        <Widget>[
          Text('item0', key: Key('0')),
          Text('item1', key: Key('1')),
412
        ],
413 414 415 416 417 418 419
      ));
      await tester.pumpWidget(const TestSliverGrid(
        <Widget>[
          Text('item0', key: Key('0')),
          Text('item3', key: Key('3')),
          Text('item4', key: Key('4')),
          Text('item1', key: Key('1')),
420
        ],
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
      ));
      expect(find.text('item0'), findsOneWidget);
      expect(find.text('item3'), findsOneWidget);
      expect(find.text('item4'), findsOneWidget);
      expect(find.text('item1'), findsOneWidget);

      final Offset item0Location = tester.getCenter(find.text('item0'));
      final Offset item3Location = tester.getCenter(find.text('item3'));
      final Offset item4Location = tester.getCenter(find.text('item4'));
      final Offset item1Location = tester.getCenter(find.text('item1'));

      expect(isRight(item0Location, item3Location) && sameHorizontal(item0Location, item3Location), true);
      expect(isBelow(item0Location, item4Location) && sameVertical(item0Location, item4Location), true);
      expect(isBelow(item0Location, item1Location) && isRight(item0Location, item1Location), true);
    },
  );

438
  testWidgets(
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    'SliverGrid negative usableCrossAxisExtent',
    (WidgetTester tester) async {
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Center(
            child: SizedBox(
              width: 4,
              height: 4,
              child: CustomScrollView(
                slivers: <Widget>[
                  SliverGrid(
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 8,
                      mainAxisSpacing: 8,
                    ),
                    delegate: SliverChildListDelegate(
                      <Widget>[
458 459 460 461
                        const Center(child: Text('A')),
                        const Center(child: Text('B')),
                        const Center(child: Text('C')),
                        const Center(child: Text('D')),
462 463 464 465 466 467 468 469 470 471 472 473 474 475
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      expect(tester.takeException(), isNull);
    },
  );

476
  testWidgets(
477 478 479 480
    'SliverList can handle inaccurate scroll offset due to changes in children list',
      (WidgetTester tester) async {
      // Regression test for https://github.com/flutter/flutter/pull/59888.
      bool skip = true;
481
      Widget buildItem(BuildContext context, int index) {
482 483 484 485 486 487 488 489 490 491 492 493 494
        return !skip || index.isEven
          ? Card(
          child: ListTile(
            title: Text(
              'item$index',
              style: const TextStyle(fontSize: 80),
            ),
          ),
        )
          : Container();
      }
      await tester.pumpWidget(
        MaterialApp(
495
          theme: ThemeData(useMaterial3: false),
496 497 498 499 500
          home: Scaffold(
            body: CustomScrollView(
              slivers: <Widget> [
                SliverList(
                  delegate: SliverChildBuilderDelegate(
501
                    buildItem,
502 503 504 505
                    childCount: 30,
                  ),
                ),
              ],
506
            ),
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
          ),
        ),
      );
      // Only even items 0~12 are on the screen.
      expect(find.text('item0'), findsOneWidget);
      expect(find.text('item12'), findsOneWidget);
      expect(find.text('item14'), findsNothing);

      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -750.0));
      await tester.pump();
      // Only even items 16~28 are on the screen.
      expect(find.text('item15'), findsNothing);
      expect(find.text('item16'), findsOneWidget);
      expect(find.text('item28'), findsOneWidget);

      skip = false;
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: CustomScrollView(
              slivers: <Widget> [
                SliverList(
                  delegate: SliverChildBuilderDelegate(
530
                    buildItem,
531 532 533 534
                    childCount: 30,
                  ),
                ),
              ],
535
            ),
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
          ),
        ),
      );

      // Only items 12~19 are on the screen.
      expect(find.text('item11'), findsNothing);
      expect(find.text('item12'), findsOneWidget);
      expect(find.text('item19'), findsOneWidget);
      expect(find.text('item20'), findsNothing);

      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0));
      await tester.pump();

      // Only items 10~16 are on the screen.
      expect(find.text('item9'), findsNothing);
      expect(find.text('item10'), findsOneWidget);
      expect(find.text('item16'), findsOneWidget);
      expect(find.text('item17'), findsNothing);

      // The inaccurate scroll offset should reach zero at this point
      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0));
      await tester.pump();

      // Only items 7~13 are on the screen.
      expect(find.text('item6'), findsNothing);
      expect(find.text('item7'), findsOneWidget);
      expect(find.text('item13'), findsOneWidget);
      expect(find.text('item14'), findsNothing);

      // It will be corrected as we scroll, so we have to drag multiple times.
      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0));
      await tester.pump();
      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0));
      await tester.pump();
      await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0));
      await tester.pump();

      // Only items 0~6 are on the screen.
      expect(find.text('item0'), findsOneWidget);
      expect(find.text('item6'), findsOneWidget);
      expect(find.text('item7'), findsNothing);
    },
  );

580
  testWidgets(
581 582
    'SliverFixedExtentList Correctly layout children after rearranging',
    (WidgetTester tester) async {
583 584 585 586 587
      await tester.pumpWidget(const TestSliverFixedExtentList(
          <Widget>[
            Text('item0', key: Key('0')),
            Text('item2', key: Key('2')),
            Text('item1', key: Key('1')),
588
          ],
589 590 591 592 593 594 595 596
      ));
      await tester.pumpWidget(const TestSliverFixedExtentList(
          <Widget>[
            Text('item0', key: Key('0')),
            Text('item3', key: Key('3')),
            Text('item1', key: Key('1')),
            Text('item4', key: Key('4')),
            Text('item2', key: Key('2')),
597
          ],
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
      ));
      expect(find.text('item0'), findsOneWidget);
      expect(find.text('item3'), findsOneWidget);
      expect(find.text('item1'), findsOneWidget);
      expect(find.text('item4'), findsOneWidget);
      expect(find.text('item2'), findsOneWidget);

      final Offset item0Location = tester.getCenter(find.text('item0'));
      final Offset item3Location = tester.getCenter(find.text('item3'));
      final Offset item1Location = tester.getCenter(find.text('item1'));
      final Offset item4Location = tester.getCenter(find.text('item4'));
      final Offset item2Location = tester.getCenter(find.text('item2'));

      expect(isBelow(item0Location, item3Location) && sameVertical(item0Location, item3Location), true);
      expect(isBelow(item3Location, item1Location) && sameVertical(item3Location, item1Location), true);
      expect(isBelow(item1Location, item4Location) && sameVertical(item1Location, item4Location), true);
      expect(isBelow(item4Location, item2Location) && sameVertical(item4Location, item2Location), true);
    },
  );

618
  testWidgets('Can override ErrorWidget.build', (WidgetTester tester) async {
619 620 621 622 623 624 625 626 627
    const Text errorText = Text('error');
    final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder;
    ErrorWidget.builder = (FlutterErrorDetails details) => errorText;
    final SliverChildBuilderDelegate builderThrowsDelegate = SliverChildBuilderDelegate(
      (_, __) => throw 'builder',
      addAutomaticKeepAlives: false,
      addRepaintBoundaries: false,
      addSemanticIndexes: false,
    );
628
    final KeyedSubtree wrapped = builderThrowsDelegate.build(_NullBuildContext(), 0)! as KeyedSubtree;
629
    expect(wrapped.child, errorText);
630 631 632
    expect(tester.takeException(), 'builder');
    ErrorWidget.builder = oldBuilder;
  });
633

634
  testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - super fast', (WidgetTester tester) async {
635
    final ScrollController controller = ScrollController(initialScrollOffset: 600);
636 637
    addTearDown(controller.dispose);

638 639 640 641 642 643 644 645 646 647
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: CustomScrollView(
          controller: controller,
          cacheExtent: 0,
          slivers: <Widget>[
            SliverFixedExtentList(
              itemExtent: 200,
              delegate: SliverChildBuilderDelegate(
648
                (BuildContext context, int index) {
649 650 651 652 653 654
                  if (index <= 6) {
                    return Center(child: Text('Page $index'));
                  }
                  return null;
                },
              ),
655
            ),
656 657
          ],
        ),
658
      ),
659
    );
660 661 662
    expect(find.text('Page 0'), findsNothing);
    expect(find.text('Page 6'), findsNothing);

663
    await tester.drag(find.text('Page 5'), const Offset(0, -1000));
664 665 666 667 668
    // Controller will be temporarily over-scrolled (before the frame triggered by the drag) because
    // SliverFixedExtentList doesn't report its size until it has built its last child, so the
    // maxScrollExtent is infinite, so when we move by 1000 pixels in one go, we go all the way.
    //
    // This never actually gets rendered, it's just the controller state before we lay out.
669
    expect(controller.offset, 1600.0);
670 671 672 673 674 675 676 677 678 679

    // However, once we pump, the scroll offset gets clamped to the newly discovered maximum, which
    // is the itemExtent (200) times the number of items (7) minus the height of the viewport (600).
    // This adds up to 800.0.
    await tester.pump();
    expect(find.text('Page 0'), findsNothing);
    expect(find.text('Page 6'), findsOneWidget);
    expect(controller.offset, 800.0);

    expect(await tester.pumpAndSettle(), 1); // there should be no animation here
680 681 682
    expect(controller.offset, 800.0);
  });

683
  testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - reasonable', (WidgetTester tester) async {
684
    final ScrollController controller = ScrollController(initialScrollOffset: 600);
685 686
    addTearDown(controller.dispose);

687 688 689 690 691 692 693 694 695 696
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: CustomScrollView(
          controller: controller,
          cacheExtent: 0,
          slivers: <Widget>[
            SliverFixedExtentList(
              itemExtent: 200,
              delegate: SliverChildBuilderDelegate(
697
                (BuildContext context, int index) {
698 699 700 701 702 703
                  if (index <= 6) {
                    return Center(child: Text('Page $index'));
                  }
                  return null;
                },
              ),
704
            ),
705 706
          ],
        ),
707
      ),
708 709 710 711 712 713 714 715
    );
    await tester.drag(find.text('Page 5'), const Offset(0, -210));
    // Controller will be temporarily over-scrolled.
    expect(controller.offset, 810.0);
    await tester.pumpAndSettle();
    // It will be corrected after a auto scroll animation.
    expect(controller.offset, 800.0);
  });
716

717
  Widget boilerPlate(Widget sliver) {
Kate Lovett's avatar
Kate Lovett committed
718 719 720 721 722 723 724 725 726 727
    return Localizations(
      locale: const Locale('en', 'us'),
      delegates: const <LocalizationsDelegate<dynamic>>[
        DefaultWidgetsLocalizations.delegate,
        DefaultMaterialLocalizations.delegate,
      ],
      child: Directionality(
        textDirection: TextDirection.ltr,
        child: MediaQuery(
          data: const MediaQueryData(),
728 729 730
          child: CustomScrollView(slivers: <Widget>[sliver]),
        ),
      ),
Kate Lovett's avatar
Kate Lovett committed
731 732 733
    );
  }

Kate Lovett's avatar
Kate Lovett committed
734
  group('SliverOffstage - ', () {
735
    testWidgets('offstage true', (WidgetTester tester) async {
Kate Lovett's avatar
Kate Lovett committed
736
      final SemanticsTester semantics = SemanticsTester(tester);
737
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
738 739 740
        const SliverOffstage(
          sliver: SliverToBoxAdapter(
            child: Text('a'),
741 742
          ),
        ),
Kate Lovett's avatar
Kate Lovett committed
743 744 745 746
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(0));
      expect(find.byType(Text), findsNothing);
747
      final RenderViewport renderViewport = tester.renderObject(find.byType(Viewport));
748 749
      final RenderSliver renderSliver = renderViewport.lastChild!;
      expect(renderSliver.geometry!.scrollExtent, 0.0);
750
      expect(find.byType(SliverOffstage), findsNothing);
751
      semantics.dispose();
Kate Lovett's avatar
Kate Lovett committed
752 753
    });

754
    testWidgets('offstage false', (WidgetTester tester) async {
Kate Lovett's avatar
Kate Lovett committed
755
      final SemanticsTester semantics = SemanticsTester(tester);
756
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
757 758 759 760
        const SliverOffstage(
          offstage: false,
          sliver: SliverToBoxAdapter(
            child: Text('a'),
761 762
          ),
        ),
Kate Lovett's avatar
Kate Lovett committed
763 764 765 766
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(Text), findsOneWidget);
767
      final RenderViewport renderViewport = tester.renderObject(find.byType(Viewport));
768 769
      final RenderSliver renderSliver = renderViewport.lastChild!;
      expect(renderSliver.geometry!.scrollExtent, 14.0);
770
      expect(find.byType(SliverOffstage), paints..paragraph());
771
      semantics.dispose();
Kate Lovett's avatar
Kate Lovett committed
772 773 774
    });
  });

Kate Lovett's avatar
Kate Lovett committed
775
  group('SliverOpacity - ', () {
776
    testWidgets('painting & semantics', (WidgetTester tester) async {
Kate Lovett's avatar
Kate Lovett committed
777 778 779
      final SemanticsTester semantics = SemanticsTester(tester);

      // Opacity 1.0: Semantics and painting
780
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
781 782 783 784 785
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
786
            ),
Kate Lovett's avatar
Kate Lovett committed
787 788 789 790 791 792 793 794 795
          ),
          opacity: 1.0,
        ),
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(SliverOpacity), paints..paragraph());

      // Opacity 0.0: Nothing
796
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
797 798 799 800 801
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
802
            ),
Kate Lovett's avatar
Kate Lovett committed
803 804
          ),
          opacity: 0.0,
805
        ),
Kate Lovett's avatar
Kate Lovett committed
806 807 808 809 810 811
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(0));
      expect(find.byType(SliverOpacity), paintsNothing);

      // Opacity 0.0 with semantics: Just semantics
812
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
813 814 815 816 817
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
818
            ),
Kate Lovett's avatar
Kate Lovett committed
819 820 821 822 823 824 825 826 827 828
          ),
          opacity: 0.0,
          alwaysIncludeSemantics: true,
        ),
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(SliverOpacity), paintsNothing);

      // Opacity 0.0 without semantics: Nothing
829
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
830 831 832 833 834
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
835
            ),
Kate Lovett's avatar
Kate Lovett committed
836 837 838 839
          ),
          opacity: 0.0,
        ),
      ));
840

Kate Lovett's avatar
Kate Lovett committed
841 842 843 844
      expect(semantics.nodesWith(label: 'a'), hasLength(0));
      expect(find.byType(SliverOpacity), paintsNothing);

      // Opacity 0.1: Semantics and painting
845
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
846 847 848 849 850
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
851
            ),
Kate Lovett's avatar
Kate Lovett committed
852 853 854 855 856 857 858 859 860
          ),
          opacity: 0.1,
        ),
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(SliverOpacity), paints..paragraph());

      // Opacity 0.1 without semantics: Still has semantics and painting
861
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
862 863 864 865 866
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
867
            ),
Kate Lovett's avatar
Kate Lovett committed
868 869 870 871 872 873 874 875 876
          ),
          opacity: 0.1,
        ),
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(SliverOpacity), paints..paragraph());

      // Opacity 0.1 with semantics: Semantics and painting
877
      await tester.pumpWidget(boilerPlate(
Kate Lovett's avatar
Kate Lovett committed
878 879 880 881 882
        const SliverOpacity(
          sliver: SliverToBoxAdapter(
            child: Text(
              'a',
              textDirection: TextDirection.rtl,
883
            ),
Kate Lovett's avatar
Kate Lovett committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897
          ),
          opacity: 0.1,
          alwaysIncludeSemantics: true,
        ),
      ));

      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      expect(find.byType(SliverOpacity), paints..paragraph());

      semantics.dispose();
    });
  });

  group('SliverIgnorePointer - ', () {
898
    testWidgets('ignores pointer events', (WidgetTester tester) async {
899 900
      final SemanticsTester semantics = SemanticsTester(tester);
      final List<String> events = <String>[];
901
      await tester.pumpWidget(boilerPlate(
902 903 904 905 906 907 908 909
        SliverIgnorePointer(
          ignoringSemantics: false,
          sliver: SliverToBoxAdapter(
            child: GestureDetector(
              child: const Text('a'),
              onTap: () {
                events.add('tap');
              },
910 911 912
            ),
          ),
        ),
913 914
      ));
      expect(semantics.nodesWith(label: 'a'), hasLength(1));
915
      await tester.tap(find.byType(GestureDetector), warnIfMissed: false);
916
      expect(events, equals(<String>[]));
917
      semantics.dispose();
918 919
    });

920
    testWidgets('ignores semantics', (WidgetTester tester) async {
921 922
      final SemanticsTester semantics = SemanticsTester(tester);
      final List<String> events = <String>[];
923
      await tester.pumpWidget(boilerPlate(
924 925 926 927 928 929 930 931 932
        SliverIgnorePointer(
          ignoring: false,
          ignoringSemantics: true,
          sliver: SliverToBoxAdapter(
            child: GestureDetector(
              child: const Text('a'),
              onTap: () {
                events.add('tap');
              },
933 934 935
            ),
          ),
        ),
936 937 938 939
      ));
      expect(semantics.nodesWith(label: 'a'), hasLength(0));
      await tester.tap(find.byType(GestureDetector));
      expect(events, equals(<String>['tap']));
940
      semantics.dispose();
941 942
    });

943
    testWidgets('ignoring only block semantics actions', (WidgetTester tester) async {
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(boilerPlate(
        SliverIgnorePointer(
          sliver: SliverToBoxAdapter(
            child: GestureDetector(
              child: const Text('a'),
              onTap: () { },
            ),
          ),
        ),
      ));
      expect(semantics, includesNodeWith(label: 'a', actions: <SemanticsAction>[]));
      semantics.dispose();
    });

959
    testWidgets('ignores pointer events & semantics', (WidgetTester tester) async {
960 961
      final SemanticsTester semantics = SemanticsTester(tester);
      final List<String> events = <String>[];
962
      await tester.pumpWidget(boilerPlate(
963 964 965 966 967 968 969 970
        SliverIgnorePointer(
          ignoringSemantics: true,
          sliver: SliverToBoxAdapter(
            child: GestureDetector(
              child: const Text('a'),
              onTap: () {
                events.add('tap');
              },
971 972 973
            ),
          ),
        ),
974 975
      ));
      expect(semantics.nodesWith(label: 'a'), hasLength(0));
976
      await tester.tap(find.byType(GestureDetector), warnIfMissed: false);
977
      expect(events, equals(<String>[]));
978
      semantics.dispose();
979 980
    });

981
    testWidgets('ignores nothing', (WidgetTester tester) async {
982 983
      final SemanticsTester semantics = SemanticsTester(tester);
      final List<String> events = <String>[];
984
      await tester.pumpWidget(boilerPlate(
985 986 987 988 989 990 991 992 993
        SliverIgnorePointer(
          ignoring: false,
          ignoringSemantics: false,
          sliver: SliverToBoxAdapter(
            child: GestureDetector(
              child: const Text('a'),
              onTap: () {
                events.add('tap');
              },
994 995 996
            ),
          ),
        ),
997 998 999 1000
      ));
      expect(semantics.nodesWith(label: 'a'), hasLength(1));
      await tester.tap(find.byType(GestureDetector));
      expect(events, equals(<String>['tap']));
1001
      semantics.dispose();
1002 1003
    });
  });
1004

1005
  testWidgets('SliverList handles 0 scrollOffsetCorrection', (WidgetTester tester) async {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
    // Regression test for https://github.com/flutter/flutter/issues/62198
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildListDelegate(
                const <Widget>[
                  SizedBox.shrink(),
                  Text('index 1'),
                  Text('index 2'),
1018
                ],
1019 1020 1021
              ),
            ),
          ],
1022
        ),
1023 1024 1025 1026 1027 1028
      ),
    ));
    await tester.fling(find.byType(Scrollable), const Offset(0.0, -500.0), 10000.0);
    await tester.pumpAndSettle();
    expect(tester.takeException(), isNull);
  });
1029

1030
  testWidgets('SliverGrid children can be arbitrarily placed', (WidgetTester tester) async {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    // Regression test for https://github.com/flutter/flutter/issues/64006
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverGrid(
              delegate: SliverChildBuilderDelegate(
1042
                (BuildContext context, int index) {
1043 1044 1045 1046 1047 1048 1049
                  return Material(
                    color: index.isEven ? Colors.yellow : Colors.red,
                    child: InkWell(
                      onTap: () {
                        index.isEven ? firstTapped++ : secondTapped++;
                      },
                      child: Text('Index $index'),
1050 1051 1052 1053 1054 1055
                    ),
                  );
                },
                childCount: 2,
              ),
              gridDelegate: _TestArbitrarySliverGridDelegate(),
1056
            ),
1057 1058
          ],
        ),
1059
      ),
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    ));
    // Assertion not triggered by arbitrary placement
    expect(tester.takeException(), isNull);

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 1);
    expect(secondTapped, 1);
    // Check other places too
    final Offset bottomLeft = tester.getBottomLeft(find.byKey(key));
    await tester.tapAt(bottomLeft);
    expect(firstTapped, 1);
    expect(secondTapped, 1);
    final Offset topRight = tester.getTopRight(find.byKey(key));
    await tester.tapAt(topRight);
    expect(firstTapped, 1);
    expect(secondTapped, 1);
    await tester.tapAt(const Offset(100.0, 100.0));
    expect(firstTapped, 1);
    expect(secondTapped, 1);
    await tester.tapAt(const Offset(700.0, 500.0));
    expect(firstTapped, 1);
    expect(secondTapped, 1);
  });
1087

1088
  testWidgets('SliverList.builder can build children', (WidgetTester tester) async {
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverList.builder(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                return Material(
                  color: index.isEven ? Colors.yellow : Colors.red,
                  child: InkWell(
                    onTap: () {
                      index.isEven ? firstTapped++ : secondTapped++;
                    },
                    child: Text('Index $index'),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1126
  testWidgets('SliverList.builder can build children', (WidgetTester tester) async {
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverList.builder(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                return Material(
                  color: index.isEven ? Colors.yellow : Colors.red,
                  child: InkWell(
                    onTap: () {
                      index.isEven ? firstTapped++ : secondTapped++;
                    },
                    child: Text('Index $index'),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1164
  testWidgets('SliverList.separated can build children', (WidgetTester tester) async {
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverList.separated(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                return Material(
                  color: index.isEven ? Colors.yellow : Colors.red,
                  child: InkWell(
                    onTap: () {
                      index.isEven ? firstTapped++ : secondTapped++;
                    },
                    child: Text('Index $index'),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) => Text('Separator $index'),
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1203
  testWidgets('SliverList.separated has correct number of children', (WidgetTester tester) async {
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverList.separated(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) => const Text('item'),
              separatorBuilder: (BuildContext context, int index) => const Text('separator'),
            ),
          ],
        ),
      ),
    ));
    expect(find.text('item'), findsNWidgets(2));
    expect(find.text('separator'), findsNWidgets(1));
  });

1223
  testWidgets('SliverList.list can build children', (WidgetTester tester) async {
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverList.list(
              children: <Widget>[
                Material(
                  color: Colors.yellow,
                  child: InkWell(
                    onTap: () => firstTapped++,
                    child: const Text('Index 0'),
                  ),
                ),
                Material(
                  color: Colors.red,
                  child: InkWell(
                    onTap: () => secondTapped++,
                    child: const Text('Index 1'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1265
  testWidgets('SliverFixedExtentList.builder can build children', (WidgetTester tester) async {
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverFixedExtentList.builder(
              itemCount: 2,
              itemExtent: 100,
              itemBuilder: (BuildContext context, int index) {
                return Material(
                  color: index.isEven ? Colors.yellow : Colors.red,
                  child: InkWell(
                    onTap: () {
                      index.isEven ? firstTapped++ : secondTapped++;
                    },
                    child: Text('Index $index'),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    ));
    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1303
    testWidgets('SliverList.list can build children', (WidgetTester tester) async {
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverFixedExtentList.list(
              itemExtent: 100,
              children: <Widget>[
                Material(
                  color: Colors.yellow,
                  child: InkWell(
                    onTap: () => firstTapped++,
                    child: const Text('Index 0'),
                  ),
                ),
                Material(
                  color: Colors.red,
                  child: InkWell(
                    onTap: () => secondTapped++,
                    child: const Text('Index 1'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });

1346
  testWidgets('SliverGrid.builder can build children', (WidgetTester tester) async {
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    int firstTapped = 0;
    int secondTapped = 0;
    final Key key = UniqueKey();
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        key: key,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverGrid.builder(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                  return Material(
                    color: index.isEven ? Colors.yellow : Colors.red,
                    child: InkWell(
                      onTap: () {
                        index.isEven ? firstTapped++ : secondTapped++;
                      },
                      child: Text('Index $index'),
                    ),
                  );
                },
              gridDelegate: _TestArbitrarySliverGridDelegate(),
            ),
          ],
        ),
      ),
    ));

    // Verify correct hit testing
    await tester.tap(find.text('Index 0'));
    expect(firstTapped, 1);
    expect(secondTapped, 0);
    firstTapped = 0;
    await tester.tap(find.text('Index 1'));
    expect(firstTapped, 0);
    expect(secondTapped, 1);
  });
1384

1385
  testWidgets('SliverGridRegularTileLayout.computeMaxScrollOffset handles 0 children', (WidgetTester tester) async {
1386 1387
    // Regression test for https://github.com/flutter/flutter/issues/59663
    final ScrollController controller = ScrollController();
1388
    addTearDown(controller.dispose);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

    // SliverGridDelegateWithFixedCrossAxisCount
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          controller: controller,
          slivers: <Widget>[
            SliverGrid.builder(
              itemCount: 0,
              itemBuilder: (_, __) => Container(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,
                mainAxisSpacing: 10,
                childAspectRatio: 2.1,
              ),
            ),
          ],
        ),
      ),
    ));

    // Verify correct scroll extent
    expect(controller.position.maxScrollExtent, 0.0);

    // SliverGridDelegateWithMaxCrossAxisExtent
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          controller: controller,
          slivers: <Widget>[
            SliverGrid.builder(
              itemCount: 0,
              itemBuilder: (_, __) => Container(),
              gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 30,
              ),
            ),
          ],
        ),
      ),
    ));

    // Verify correct scroll extent
    expect(controller.position.maxScrollExtent, 0.0);
  });
1434
}
1435 1436 1437 1438 1439 1440 1441

bool isRight(Offset a, Offset b) => b.dx > a.dx;
bool isBelow(Offset a, Offset b) => b.dy > a.dy;
bool sameHorizontal(Offset a, Offset b) => b.dy == a.dy;
bool sameVertical(Offset a, Offset b) => b.dx == a.dx;

class TestSliverGrid extends StatelessWidget {
1442
  const TestSliverGrid(this.children, { super.key });
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460

  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: CustomScrollView(
        slivers: <Widget> [
          SliverGrid(
            delegate: SliverChildListDelegate(
              children,
            ),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
            ),
          ),
        ],
1461
      ),
1462 1463 1464 1465
    );
  }
}

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
class _TestArbitrarySliverGridDelegate implements SliverGridDelegate {
  @override
  SliverGridLayout getLayout(SliverConstraints constraints) {
    return _TestArbitrarySliverGridLayout();
  }

  @override
  bool shouldRelayout(SliverGridDelegate oldDelegate) {
    return false;
  }
}

class _TestArbitrarySliverGridLayout implements SliverGridLayout {
  @override
  double computeMaxScrollOffset(int childCount) => 1000;

  @override
  int getMinChildIndexForScrollOffset(double scrollOffset) => 0;

  @override
  int getMaxChildIndexForScrollOffset(double scrollOffset) => 2;

  @override
  SliverGridGeometry getGeometryForChildIndex(int index) {
    return SliverGridGeometry(
      scrollOffset: index * 100.0 + 300.0,
      crossAxisOffset: 200.0,
      mainAxisExtent: 100.0,
      crossAxisExtent: 100.0,
    );
  }
}

1499
class TestSliverFixedExtentList extends StatelessWidget {
1500
  const TestSliverFixedExtentList(this.children, { super.key });
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516

  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    return Directionality(
        textDirection: TextDirection.ltr,
        child: CustomScrollView(
          slivers: <Widget> [
            SliverFixedExtentList(
              itemExtent: 10.0,
              delegate: SliverChildListDelegate(
                children,
              ),
            ),
          ],
1517
        ),
1518 1519 1520
    );
  }
}
1521

1522
class StateInitSpy extends StatefulWidget {
1523
  const StateInitSpy(this.data, this.onStateInit, { super.key });
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544

  final String data;
  final VoidCallback onStateInit;

  @override
  StateInitSpyState createState() => StateInitSpyState();
}

class StateInitSpyState extends State<StateInitSpy> {
  @override
  void initState() {
    super.initState();
    widget.onStateInit();
  }

  @override
  Widget build(BuildContext context) {
    return Text(widget.data);
  }
}

1545
class KeepAlive extends StatefulWidget {
1546
  const KeepAlive(this.data, { super.key });
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

  final String data;

  @override
  KeepAliveState createState() => KeepAliveState();
}

class KeepAliveState extends State<KeepAlive> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Text(widget.data);
  }
}
1564 1565 1566 1567 1568

class _NullBuildContext implements BuildContext {
  @override
  dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
}
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621

class TestGridDelegate implements SliverGridDelegate {
  TestGridDelegate(this.replace);

  final bool replace;

  @override
  SliverGridLayout getLayout(SliverConstraints constraints) {
    return TestGridLayout(replace);
  }

  @override
  bool shouldRelayout(covariant TestGridDelegate oldDelegate) {
    return true;
  }
}

class TestGridLayout implements SliverGridLayout {
  TestGridLayout(this.replace);

  final bool replace;

  @override
  double computeMaxScrollOffset(int childCount) {
    return 200;
  }

  @override
  SliverGridGeometry getGeometryForChildIndex(int index) {
    return SliverGridGeometry(
      crossAxisOffset: 20.0 + 20 * index,
      crossAxisExtent: 20,
      mainAxisExtent: 20,
      scrollOffset: 0,
    );
  }

  @override
  int getMaxChildIndexForScrollOffset(double scrollOffset) {
    if (replace) {
      return 1;
    }
    return 5;
  }

  @override
  int getMinChildIndexForScrollOffset(double scrollOffset) {
    if (replace) {
      return 1;
    }
    return 0;
  }
}