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

5
import 'package:flutter/gestures.dart' show DragStartBehavior;
6
import 'package:flutter/material.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter_test/flutter_test.dart';
Adam Barth's avatar
Adam Barth committed
9

10
import '../rendering/rendering_tester.dart' show TestClipPaintingContext;
11
import 'semantics_tester.dart';
Adam Barth's avatar
Adam Barth committed
12 13 14
import 'states.dart';

void main() {
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  // Regression test for https://github.com/flutter/flutter/issues/100451
  testWidgets('PageView.builder respects findChildIndexCallback', (WidgetTester tester) async {
    bool finderCalled = false;
    int itemCount = 7;
    late StateSetter stateSetter;

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            stateSetter = setState;
            return PageView.builder(
              itemCount: itemCount,
              itemBuilder: (BuildContext _, int index) => Container(
                key: Key('$index'),
                height: 2000.0,
              ),
              findChildIndexCallback: (Key key) {
                finderCalled = true;
                return null;
              },
            );
          },
        ),
      )
    );
    expect(finderCalled, false);

    // Trigger update.
    stateSetter(() => itemCount = 77);
    await tester.pump();

    expect(finderCalled, true);
  });

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  testWidgets('PageView resize from zero-size viewport should not lose state', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/88956
    final PageController controller = PageController(
      initialPage: 1,
    );

    Widget build(Size size) {
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: SizedBox.fromSize(
            size: size,
            child: PageView(
              controller: controller,
              onPageChanged: (int page) { },
66
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
            ),
          ),
        ),
      );
    }

    // The pageView have a zero viewport, so nothing display.
    await tester.pumpWidget(build(Size.zero));
    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alabama', skipOffstage: false), findsOneWidget);

    // Resize from zero viewport to non-zero, the controller's initialPage 1 will display.
    await tester.pumpWidget(build(const Size(200.0, 200.0)));
    expect(find.text('Alaska'), findsOneWidget);

    // Jump to page 'Iowa'.
    controller.jumpToPage(kStates.indexOf('Iowa'));
    await tester.pump();
    expect(find.text('Iowa'), findsOneWidget);

    // Resize to zero viewport again, nothing display.
    await tester.pumpWidget(build(Size.zero));
    expect(find.text('Iowa'), findsNothing);

    // Resize from zero to non-zero, the pageView should not lose state, so the page 'Iowa' show again.
    await tester.pumpWidget(build(const Size(200.0, 200.0)));
    expect(find.text('Iowa'), findsOneWidget);
  });

  testWidgets('Change the page through the controller when zero-size viewport', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/88956
    final PageController controller = PageController(
      initialPage: 1,
    );

    Widget build(Size size) {
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: SizedBox.fromSize(
            size: size,
            child: PageView(
              controller: controller,
              onPageChanged: (int page) { },
111
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            ),
          ),
        ),
      );
    }

    // The pageView have a zero viewport, so nothing display.
    await tester.pumpWidget(build(Size.zero));
    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alabama', skipOffstage: false), findsOneWidget);

    // Change the page through the page controller when zero viewport
    controller.animateToPage(kStates.indexOf('Iowa'), duration: kTabScrollDuration, curve: Curves.ease);
    expect(controller.page, kStates.indexOf('Iowa'));

    controller.jumpToPage(kStates.indexOf('Illinois'));
    expect(controller.page, kStates.indexOf('Illinois'));

    // Resize from zero viewport to non-zero, the latest state should not lost.
    await tester.pumpWidget(build(const Size(200.0, 200.0)));
    expect(controller.page, kStates.indexOf('Illinois'));
    expect(find.text('Illinois'), findsOneWidget);
  });

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  testWidgets('_PagePosition.applyViewportDimension should not throw', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/101007
    final PageController controller = PageController(
      initialPage: 1,
    );

    // Set the starting viewportDimension to 0.0
    await tester.binding.setSurfaceSize(Size.zero);
    final MediaQueryData mediaQueryData = MediaQueryData.fromWindow(tester.binding.window);

    Widget build(Size size) {
      return MediaQuery(
        data: mediaQueryData.copyWith(size: size),
        child: Directionality(
          textDirection: TextDirection.ltr,
          child: Center(
            child: SizedBox.expand(
              child: PageView(
                controller: controller,
                onPageChanged: (int page) { },
                children: kStates.map<Widget>((String state) => Text(state)).toList(),
              ),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(build(Size.zero));
    const Size surfaceSize = Size(500,400);
    await tester.binding.setSurfaceSize(surfaceSize);
    await tester.pumpWidget(build(surfaceSize));

    expect(tester.takeException(), isNull);

    // Reset TestWidgetsFlutterBinding surfaceSize
    await tester.binding.setSurfaceSize(null);
  });

175 176 177 178 179 180
  testWidgets('PageController cannot return page while unattached',
      (WidgetTester tester) async {
    final PageController controller = PageController();
    expect(() => controller.page, throwsAssertionError);
  });

Adam Barth's avatar
Adam Barth committed
181
  testWidgets('PageView control test', (WidgetTester tester) async {
182
    final List<String> log = <String>[];
Adam Barth's avatar
Adam Barth committed
183

184
    await tester.pumpWidget(Directionality(
185
      textDirection: TextDirection.ltr,
186
      child: PageView(
187
        dragStartBehavior: DragStartBehavior.down,
188
        children: kStates.map<Widget>((String state) {
189
          return GestureDetector(
190
            dragStartBehavior: DragStartBehavior.down,
191 192 193
            onTap: () {
              log.add(state);
            },
194
            child: Container(
195 196
              height: 200.0,
              color: const Color(0xFF0000FF),
197
              child: Text(state),
198 199 200 201
            ),
          );
        }).toList(),
      ),
Adam Barth's avatar
Adam Barth committed
202 203 204 205 206 207 208 209
    ));

    await tester.tap(find.text('Alabama'));
    expect(log, equals(<String>['Alabama']));
    log.clear();

    expect(find.text('Alaska'), findsNothing);

210
    await tester.drag(find.byType(PageView), const Offset(-20.0, 0.0));
Adam Barth's avatar
Adam Barth committed
211 212 213 214 215 216
    await tester.pump();

    expect(find.text('Alabama'), findsOneWidget);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsNothing);

217
    await tester.pumpAndSettle();
Adam Barth's avatar
Adam Barth committed
218 219 220 221

    expect(find.text('Alabama'), findsOneWidget);
    expect(find.text('Alaska'), findsNothing);

222
    await tester.drag(find.byType(PageView), const Offset(-401.0, 0.0));
223
    await tester.pumpAndSettle();
Adam Barth's avatar
Adam Barth committed
224 225 226 227 228 229 230 231 232

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsNothing);

    await tester.tap(find.text('Alaska'));
    expect(log, equals(<String>['Alaska']));
    log.clear();

233
    await tester.fling(find.byType(PageView), const Offset(-200.0, 0.0), 1000.0);
234
    await tester.pumpAndSettle();
Adam Barth's avatar
Adam Barth committed
235 236 237 238 239 240

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsNothing);
    expect(find.text('Arizona'), findsOneWidget);

    await tester.fling(find.byType(PageView), const Offset(200.0, 0.0), 1000.0);
241
    await tester.pumpAndSettle();
Adam Barth's avatar
Adam Barth committed
242 243 244 245 246

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsNothing);
  });
247

248
  testWidgets('PageView does not squish when overscrolled', (WidgetTester tester) async {
249 250 251 252 253
    await tester.pumpWidget(MaterialApp(
      home: PageView(
        children: List<Widget>.generate(10, (int i) {
          return Container(
            key: ValueKey<int>(i),
254
            color: const Color(0xFF0000FF),
255 256 257 258 259
          );
        }),
      ),
    ));

260 261
    Size sizeOf(int i) => tester.getSize(find.byKey(ValueKey<int>(i)));
    double leftOf(int i) => tester.getTopLeft(find.byKey(ValueKey<int>(i))).dx;
262 263 264 265

    expect(leftOf(0), equals(0.0));
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));

266
    // Going into overscroll.
267
    await tester.drag(find.byType(PageView), const Offset(100.0, 0.0));
268 269
    await tester.pump();

270
    expect(leftOf(0), greaterThan(0.0));
271 272
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));

273
    // Easing overscroll past overscroll limit.
274
    await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0));
275 276
    await tester.pump();

277
    expect(leftOf(0), lessThan(0.0));
278
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));
Dan Field's avatar
Dan Field committed
279
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
280 281

  testWidgets('PageController control test', (WidgetTester tester) async {
282
    final PageController controller = PageController(initialPage: 4);
283

284
    await tester.pumpWidget(Directionality(
285
      textDirection: TextDirection.ltr,
286 287
      child: Center(
        child: SizedBox(
288 289
          width: 600.0,
          height: 400.0,
290
          child: PageView(
291
            controller: controller,
292
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
293
          ),
294 295 296 297 298 299
        ),
      ),
    ));

    expect(find.text('California'), findsOneWidget);

300
    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
301
    await tester.pumpAndSettle();
302 303 304

    expect(find.text('Colorado'), findsOneWidget);

305
    await tester.pumpWidget(Directionality(
306
      textDirection: TextDirection.ltr,
307 308
      child: Center(
        child: SizedBox(
309 310
          width: 300.0,
          height: 400.0,
311
          child: PageView(
312
            controller: controller,
313
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
314
          ),
315 316 317 318 319 320
        ),
      ),
    ));

    expect(find.text('Colorado'), findsOneWidget);

321
    controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
322
    await tester.pumpAndSettle();
323 324 325 326 327

    expect(find.text('California'), findsOneWidget);
  });

  testWidgets('PageController page stability', (WidgetTester tester) async {
328
    await tester.pumpWidget(Directionality(
329
      textDirection: TextDirection.ltr,
330 331
      child: Center(
        child: SizedBox(
332 333
          width: 600.0,
          height: 400.0,
334 335
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
336
          ),
337
        ),
338 339 340 341 342
      ),
    ));

    expect(find.text('Alabama'), findsOneWidget);

343
    await tester.drag(find.byType(PageView), const Offset(-1250.0, 0.0));
344
    await tester.pumpAndSettle();
345 346 347

    expect(find.text('Arizona'), findsOneWidget);

348
    await tester.pumpWidget(Directionality(
349
      textDirection: TextDirection.ltr,
350 351
      child: Center(
        child: SizedBox(
352 353
          width: 250.0,
          height: 100.0,
354 355
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
356
          ),
357 358 359 360 361 362
        ),
      ),
    ));

    expect(find.text('Arizona'), findsOneWidget);

363
    await tester.pumpWidget(Directionality(
364
      textDirection: TextDirection.ltr,
365 366
      child: Center(
        child: SizedBox(
367 368
          width: 450.0,
          height: 400.0,
369 370
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
371
          ),
372 373 374 375 376 377
        ),
      ),
    ));

    expect(find.text('Arizona'), findsOneWidget);
  });
378

379
  testWidgets('PageController nextPage and previousPage return Futures that resolve', (WidgetTester tester) async {
380 381
    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
382
        textDirection: TextDirection.ltr,
383
        child: PageView(
384
          controller: controller,
385
          children: kStates.map<Widget>((String state) => Text(state)).toList(),
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        ),
    ));

    bool nextPageCompleted = false;
    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease)
        .then((_) => nextPageCompleted = true);

    expect(nextPageCompleted, false);
    await tester.pump(const Duration(milliseconds: 200));
    expect(nextPageCompleted, false);
    await tester.pump(const Duration(milliseconds: 200));
    expect(nextPageCompleted, true);


    bool previousPageCompleted = false;
    controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease)
        .then((_) => previousPageCompleted = true);

    expect(previousPageCompleted, false);
    await tester.pump(const Duration(milliseconds: 200));
    expect(previousPageCompleted, false);
    await tester.pump(const Duration(milliseconds: 200));
    expect(previousPageCompleted, true);
  });

411
  testWidgets('PageView in zero-size container', (WidgetTester tester) async {
412
    await tester.pumpWidget(Directionality(
413
      textDirection: TextDirection.ltr,
414 415
      child: Center(
        child: SizedBox(
416 417
          width: 0.0,
          height: 0.0,
418 419
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
420
          ),
421 422 423 424
        ),
      ),
    ));

425
    expect(find.text('Alabama', skipOffstage: false), findsOneWidget);
426

427
    await tester.pumpWidget(Directionality(
428
      textDirection: TextDirection.ltr,
429 430
      child: Center(
        child: SizedBox(
431 432
          width: 200.0,
          height: 200.0,
433 434
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
435
          ),
436 437 438 439 440
        ),
      ),
    ));

    expect(find.text('Alabama'), findsOneWidget);
441
  });
442 443 444

  testWidgets('Page changes at halfway point', (WidgetTester tester) async {
    final List<int> log = <int>[];
445
    await tester.pumpWidget(Directionality(
446
      textDirection: TextDirection.ltr,
447
      child: PageView(
448
        onPageChanged: log.add,
449
        children: kStates.map<Widget>((String state) => Text(state)).toList(),
450
      ),
451 452 453 454
    ));

    expect(log, isEmpty);

455
    final TestGesture gesture =
456
        await tester.startGesture(const Offset(100.0, 100.0));
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    // The page view is 800.0 wide, so this move is just short of halfway.
    await gesture.moveBy(const Offset(-380.0, 0.0));

    expect(log, isEmpty);

    // We've crossed the halfway mark.
    await gesture.moveBy(const Offset(-40.0, 0.0));

    expect(log, equals(const <int>[1]));
    log.clear();

    // Moving a bit more should not generate redundant notifications.
    await gesture.moveBy(const Offset(-40.0, 0.0));

    expect(log, isEmpty);

    await gesture.moveBy(const Offset(-40.0, 0.0));
    await tester.pump();

    await gesture.moveBy(const Offset(-40.0, 0.0));
    await tester.pump();

    await gesture.moveBy(const Offset(-40.0, 0.0));
    await tester.pump();

    expect(log, isEmpty);

    await gesture.up();
485
    await tester.pumpAndSettle();
486 487 488 489 490 491 492

    expect(log, isEmpty);

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsOneWidget);
  });

493 494
  testWidgets('Bouncing scroll physics ballistics does not overshoot', (WidgetTester tester) async {
    final List<int> log = <int>[];
495
    final PageController controller = PageController(viewportFraction: 0.9);
496

497
    Widget build(PageController controller, { Size? size }) {
498
      final Widget pageView = Directionality(
499
        textDirection: TextDirection.ltr,
500
        child: PageView(
501 502 503
          controller: controller,
          onPageChanged: log.add,
          physics: const BouncingScrollPhysics(),
504
          children: kStates.map<Widget>((String state) => Text(state)).toList(),
505 506 507 508
        ),
      );

      if (size != null) {
509
        return OverflowBox(
510 511 512 513
          minWidth: size.width,
          minHeight: size.height,
          maxWidth: size.width,
          maxHeight: size.height,
514
          child: pageView,
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        );
      } else {
        return pageView;
      }
    }

    await tester.pumpWidget(build(controller));
    expect(log, isEmpty);

    // Fling right to move to a non-existent page at the beginning of the
    // PageView, and confirm that the PageView settles back on the first page.
    await tester.fling(find.byType(PageView), const Offset(100.0, 0.0), 800.0);
    await tester.pumpAndSettle();
    expect(log, isEmpty);

    expect(find.text('Alabama'), findsOneWidget);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsNothing);

    // Try again with a Cupertino "Plus" device size.
    await tester.pumpWidget(build(controller, size: const Size(414.0, 736.0)));
    expect(log, isEmpty);

    await tester.fling(find.byType(PageView), const Offset(100.0, 0.0), 800.0);
    await tester.pumpAndSettle();
    expect(log, isEmpty);

    expect(find.text('Alabama'), findsOneWidget);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsNothing);
  });

547
  testWidgets('PageView viewportFraction', (WidgetTester tester) async {
548
    PageController controller = PageController(viewportFraction: 7/8);
549 550

    Widget build(PageController controller) {
551
      return Directionality(
552
        textDirection: TextDirection.ltr,
553
        child: PageView.builder(
554 555 556
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
557
            return Container(
558
              height: 200.0,
559
              color: index.isEven
560 561
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
562
              child: Text(kStates[index]),
563 564 565
            );
          },
        ),
566 567 568 569 570
      );
    }

    await tester.pumpWidget(build(controller));

571 572
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(50.0, 0.0));
    expect(tester.getTopLeft(find.text('Alaska')), const Offset(750.0, 0.0));
573 574 575 576

    controller.jumpToPage(10);
    await tester.pump();

577 578 579
    expect(tester.getTopLeft(find.text('Georgia')), const Offset(-650.0, 0.0));
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(50.0, 0.0));
    expect(tester.getTopLeft(find.text('Idaho')), const Offset(750.0, 0.0));
580

581
    controller = PageController(viewportFraction: 39/40);
582 583 584

    await tester.pumpWidget(build(controller));

585 586 587
    expect(tester.getTopLeft(find.text('Georgia')), const Offset(-770.0, 0.0));
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(10.0, 0.0));
    expect(tester.getTopLeft(find.text('Idaho')), const Offset(790.0, 0.0));
588 589
  });

590 591 592
  testWidgets('Page snapping disable and reenable', (WidgetTester tester) async {
    final List<int> log = <int>[];

593
    Widget build({ required bool pageSnapping }) {
594
      return Directionality(
595
        textDirection: TextDirection.ltr,
596
        child: PageView(
597 598 599
          pageSnapping: pageSnapping,
          onPageChanged: log.add,
          children:
600
              kStates.map<Widget>((String state) => Text(state)).toList(),
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
        ),
      );
    }

    await tester.pumpWidget(build(pageSnapping: true));
    expect(log, isEmpty);

    // Drag more than halfway to the next page, to confirm the default behavior.
    TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0));
    // The page view is 800.0 wide, so this move is just beyond halfway.
    await gesture.moveBy(const Offset(-420.0, 0.0));

    expect(log, equals(const <int>[1]));
    log.clear();

    // Release the gesture, confirm that the page settles on the next.
    await gesture.up();
    await tester.pumpAndSettle();

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsOneWidget);

    // Disable page snapping, and try moving halfway. Confirm it doesn't snap.
    await tester.pumpWidget(build(pageSnapping: false));
    gesture = await tester.startGesture(const Offset(100.0, 100.0));
    // Move just beyond halfway, again.
    await gesture.moveBy(const Offset(-420.0, 0.0));

    // Page notifications still get sent.
    expect(log, equals(const <int>[2]));
    log.clear();

    // Release the gesture, confirm that both pages are visible.
    await gesture.up();
    await tester.pumpAndSettle();

    expect(find.text('Alabama'), findsNothing);
    expect(find.text('Alaska'), findsOneWidget);
    expect(find.text('Arizona'), findsOneWidget);
    expect(find.text('Arkansas'), findsNothing);

    // Now re-enable snapping, confirm that we've settled on a page.
    await tester.pumpWidget(build(pageSnapping: true));
    await tester.pumpAndSettle();

    expect(log, isEmpty);

    expect(find.text('Alaska'), findsNothing);
    expect(find.text('Arizona'), findsOneWidget);
    expect(find.text('Arkansas'), findsNothing);
  });

653
  testWidgets('PageView small viewportFraction', (WidgetTester tester) async {
654
    final PageController controller = PageController(viewportFraction: 1/8);
655 656

    Widget build(PageController controller) {
657
      return Directionality(
658
        textDirection: TextDirection.ltr,
659
        child: PageView.builder(
660 661 662
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
663
            return Container(
664
              height: 200.0,
665
              color: index.isEven
666 667
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
668
              child: Text(kStates[index]),
669 670 671
            );
          },
        ),
672 673 674 675 676
      );
    }

    await tester.pumpWidget(build(controller));

677 678 679 680 681
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(350.0, 0.0));
    expect(tester.getTopLeft(find.text('Alaska')), const Offset(450.0, 0.0));
    expect(tester.getTopLeft(find.text('Arizona')), const Offset(550.0, 0.0));
    expect(tester.getTopLeft(find.text('Arkansas')), const Offset(650.0, 0.0));
    expect(tester.getTopLeft(find.text('California')), const Offset(750.0, 0.0));
682 683 684 685

    controller.jumpToPage(10);
    await tester.pump();

686 687 688 689 690 691 692 693 694
    expect(tester.getTopLeft(find.text('Connecticut')), const Offset(-50.0, 0.0));
    expect(tester.getTopLeft(find.text('Delaware')), const Offset(50.0, 0.0));
    expect(tester.getTopLeft(find.text('Florida')), const Offset(150.0, 0.0));
    expect(tester.getTopLeft(find.text('Georgia')), const Offset(250.0, 0.0));
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(350.0, 0.0));
    expect(tester.getTopLeft(find.text('Idaho')), const Offset(450.0, 0.0));
    expect(tester.getTopLeft(find.text('Illinois')), const Offset(550.0, 0.0));
    expect(tester.getTopLeft(find.text('Indiana')), const Offset(650.0, 0.0));
    expect(tester.getTopLeft(find.text('Iowa')), const Offset(750.0, 0.0));
695 696 697
  });

  testWidgets('PageView large viewportFraction', (WidgetTester tester) async {
698
    final PageController controller = PageController(viewportFraction: 5/4);
699 700

    Widget build(PageController controller) {
701
      return Directionality(
702
        textDirection: TextDirection.ltr,
703
        child: PageView.builder(
704 705 706
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
707
            return Container(
708
              height: 200.0,
709
              color: index.isEven
710 711
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
712
              child: Text(kStates[index]),
713 714 715
            );
          },
        ),
716 717 718 719 720
      );
    }

    await tester.pumpWidget(build(controller));

721 722
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100.0, 0.0));
    expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0));
723 724 725 726

    controller.jumpToPage(10);
    await tester.pump();

727
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-100.0, 0.0));
728
  });
729

730 731 732 733 734 735 736 737 738 739 740 741
  testWidgets(
    'Updating PageView large viewportFraction',
    (WidgetTester tester) async {
      Widget build(PageController controller) {
        return Directionality(
          textDirection: TextDirection.ltr,
          child: PageView.builder(
            controller: controller,
            itemCount: kStates.length,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                height: 200.0,
742
                color: index.isEven
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
                  ? const Color(0xFF0000FF)
                  : const Color(0xFF00FF00),
                child: Text(kStates[index]),
              );
            },
          ),
        );
      }

      final PageController oldController = PageController(viewportFraction: 5/4);
      await tester.pumpWidget(build(oldController));

      expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100, 0));
      expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0));

      final PageController newController = PageController(viewportFraction: 4);
      await tester.pumpWidget(build(newController));
      newController.jumpToPage(10);
      await tester.pump();

      expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-(4 - 1) * 800 / 2, 0));
764 765
    },
  );
766

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
  testWidgets(
    'PageView large viewportFraction can scroll to the last page and snap',
    (WidgetTester tester) async {
      // Regression test for https://github.com/flutter/flutter/issues/45096.
      final PageController controller = PageController(viewportFraction: 5/4);

      Widget build(PageController controller) {
        return Directionality(
          textDirection: TextDirection.ltr,
          child: PageView.builder(
            controller: controller,
            itemCount: 3,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                height: 200.0,
782
                color: index.isEven
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
                  ? const Color(0xFF0000FF)
                  : const Color(0xFF00FF00),
                  child: Text(index.toString()),
              );
            },
          ),
        );
      }

      await tester.pumpWidget(build(controller));

      expect(tester.getCenter(find.text('0')), const Offset(400, 300));

      controller.jumpToPage(2);
      await tester.pump();
      await tester.pumpAndSettle();

      expect(tester.getCenter(find.text('2')), const Offset(400, 300));
801 802
    },
  );
803 804 805 806 807

  testWidgets(
    'All visible pages are able to receive touch events',
    (WidgetTester tester) async {
      // Regression test for https://github.com/flutter/flutter/issues/23873.
808
      final PageController controller = PageController(viewportFraction: 1/4);
809
      late int tappedIndex;
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

      Widget build() {
        return Directionality(
          textDirection: TextDirection.ltr,
          child: PageView.builder(
            controller: controller,
            itemCount: 20,
            itemBuilder: (BuildContext context, int index) {
              return GestureDetector(
                onTap: () => tappedIndex = index,
                child: SizedBox.expand(child: Text('$index')),
              );
            },
          ),
        );
      }

      Iterable<int> visiblePages = const <int> [0, 1, 2];
      await tester.pumpWidget(build());

      // The first 3 items should be visible and tappable.
831
      for (final int index in visiblePages) {
832 833 834 835 836 837 838 839 840 841 842 843
        expect(find.text(index.toString()), findsOneWidget);
        // The center of page 2's x-coordinate is 800, so we have to manually
        // offset it a bit to make sure the tap lands within the screen.
        final Offset center = tester.getCenter(find.text('$index')) - const Offset(3, 0);
        await tester.tapAt(center);
        expect(tappedIndex, index);
      }

      controller.jumpToPage(19);
      await tester.pump();
      // The last 3 items should be visible and tappable.
      visiblePages = const <int> [17, 18, 19];
844
      for (final int index in visiblePages) {
845 846 847 848
        expect(find.text('$index'), findsOneWidget);
        await tester.tap(find.text('$index'));
        expect(tappedIndex, index);
      }
849 850
    },
  );
851

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
  testWidgets('the current item remains centered on constraint change', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/50505.
    final PageController controller = PageController(
      initialPage: kStates.length - 1,
      viewportFraction: 0.5,
    );

    Widget build(Size size) {
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: SizedBox.fromSize(
            size: size,
            child: PageView(
              controller: controller,
867
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
              onPageChanged: (int page) { },
            ),
          ),
        ),
      );
    }

    // Verifies that the last item is centered on screen.
    void verifyCentered() {
      expect(
        tester.getCenter(find.text(kStates.last)),
        offsetMoreOrLessEquals(const Offset(400, 300)),
      );
    }

    await tester.pumpWidget(build(const Size(300, 300)));
    await tester.pumpAndSettle();

    verifyCentered();

    await tester.pumpWidget(build(const Size(200, 300)));
    await tester.pumpAndSettle();

    verifyCentered();
  });

894
  testWidgets('PageView does not report page changed on overscroll', (WidgetTester tester) async {
895
    final PageController controller = PageController(
896 897
      initialPage: kStates.length - 1,
    );
898 899
    int changeIndex = 0;
    Widget build() {
900
      return Directionality(
901
        textDirection: TextDirection.ltr,
902
        child: PageView(
903
          controller: controller,
904
          children: kStates.map<Widget>((String state) => Text(state)).toList(),
905 906 907 908
          onPageChanged: (int page) {
            changeIndex = page;
          },
        ),
909 910 911 912 913 914 915 916 917 918
      );
    }

    await tester.pumpWidget(build());
    controller.jumpToPage(kStates.length * 2); // try to move beyond max range
    // change index should be zero, shouldn't fire onPageChanged
    expect(changeIndex, 0);
    await tester.pump();
    expect(changeIndex, 0);
  });
919

920
  testWidgets('PageView can restore page', (WidgetTester tester) async {
921
    final PageController controller = PageController();
922 923
    expect(
      () => controller.page,
924
      throwsA(isAssertionError.having(
925 926 927 928 929
        (AssertionError error) => error.message,
        'message',
        equals('PageController.page cannot be accessed before a PageView is built with it.'),
      )),
    );
930 931
    final PageStorageBucket bucket = PageStorageBucket();
    await tester.pumpWidget(Directionality(
932
      textDirection: TextDirection.ltr,
933
      child: PageStorage(
934
        bucket: bucket,
935
        child: PageView(
936
          key: const PageStorageKey<String>('PageView'),
937
          controller: controller,
938
          children: const <Widget>[
939 940 941
            Placeholder(),
            Placeholder(),
            Placeholder(),
942 943 944
          ],
        ),
      ),
945
    ));
946 947
    expect(controller.page, 0);
    controller.jumpToPage(2);
948
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2);
949 950
    expect(controller.page, 2);
    await tester.pumpWidget(
951
      PageStorage(
952
        bucket: bucket,
953
        child: Container(),
954 955
      ),
    );
956 957
    expect(
      () => controller.page,
958
      throwsA(isAssertionError.having(
959 960 961 962 963
        (AssertionError error) => error.message,
        'message',
        equals('PageController.page cannot be accessed before a PageView is built with it.'),
      )),
    );
964
    await tester.pumpWidget(Directionality(
965
      textDirection: TextDirection.ltr,
966
      child: PageStorage(
967
        bucket: bucket,
968
        child: PageView(
969
          key: const PageStorageKey<String>('PageView'),
970
          controller: controller,
971
          children: const <Widget>[
972 973 974
            Placeholder(),
            Placeholder(),
            Placeholder(),
975 976 977
          ],
        ),
      ),
978
    ));
979
    expect(controller.page, 2);
980

981 982
    final PageController controller2 = PageController(keepPage: false);
    await tester.pumpWidget(Directionality(
983
      textDirection: TextDirection.ltr,
984
      child: PageStorage(
985
        bucket: bucket,
986
        child: PageView(
987
          key: const PageStorageKey<String>('Check it again against your list and see consistency!'),
988
          controller: controller2,
989
          children: const <Widget>[
990 991 992
            Placeholder(),
            Placeholder(),
            Placeholder(),
993 994 995
          ],
        ),
      ),
996
    ));
997
    expect(controller2.page, 0);
998
  });
999 1000

  testWidgets('PageView exposes semantics of children', (WidgetTester tester) async {
1001
    final SemanticsTester semantics = SemanticsTester(tester);
1002

1003 1004
    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
1005
      textDirection: TextDirection.ltr,
1006
      child: PageView(
1007
          controller: controller,
1008 1009
          children: List<Widget>.generate(3, (int i) {
            return Semantics(
1010
              container: true,
1011
              child: Text('Page #$i'),
1012
            );
1013
          }),
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        ),
    ));
    expect(controller.page, 0);

    expect(semantics, includesNodeWith(label: 'Page #0'));
    expect(semantics, isNot(includesNodeWith(label: 'Page #1')));
    expect(semantics, isNot(includesNodeWith(label: 'Page #2')));

    controller.jumpToPage(1);
    await tester.pumpAndSettle();

    expect(semantics, isNot(includesNodeWith(label: 'Page #0')));
    expect(semantics, includesNodeWith(label: 'Page #1'));
    expect(semantics, isNot(includesNodeWith(label: 'Page #2')));

    controller.jumpToPage(2);
    await tester.pumpAndSettle();

    expect(semantics, isNot(includesNodeWith(label: 'Page #0')));
    expect(semantics, isNot(includesNodeWith(label: 'Page #1')));
    expect(semantics, includesNodeWith(label: 'Page #2'));

    semantics.dispose();
  });
1038 1039

  testWidgets('PageMetrics', (WidgetTester tester) async {
1040
    final PageMetrics page = PageMetrics(
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
      minScrollExtent: 100.0,
      maxScrollExtent: 200.0,
      pixels: 150.0,
      viewportDimension: 25.0,
      axisDirection: AxisDirection.right,
      viewportFraction: 1.0,
    );
    expect(page.page, 6);
    final PageMetrics page2 = page.copyWith(
      pixels: page.pixels - 100.0,
    );
    expect(page2.page, 4.0);
  });
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

  testWidgets('Page controller can handle rounding issue', (WidgetTester tester) async {
    final PageController pageController = PageController();

    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
      child: PageView(
        controller: pageController,
        children: List<Widget>.generate(3, (int i) {
          return Semantics(
            container: true,
1065
            child: Text('Page #$i'),
1066 1067 1068 1069 1070 1071 1072 1073
          );
        }),
      ),
    ));
    // Simulate precision error.
    pageController.position.jumpTo(799.99999999999);
    expect(pageController.page, 1);
  });
1074 1075 1076 1077 1078 1079 1080 1081 1082

  testWidgets('PageView can participate in a11y scrolling', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);

    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
      child: PageView(
          controller: controller,
1083
          allowImplicitScrolling: true,
1084 1085 1086
          children: List<Widget>.generate(4, (int i) {
            return Semantics(
              container: true,
1087
              child: Text('Page #$i'),
1088 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
            );
          }),
        ),
    ));
    expect(controller.page, 0);

    expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling]));
    expect(semantics, includesNodeWith(label: 'Page #0'));
    expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden]));
    expect(semantics, isNot(includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden])));
    expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])));

    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
    await tester.pumpAndSettle();
    expect(semantics, includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden]));
    expect(semantics, includesNodeWith(label: 'Page #1'));
    expect(semantics, includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden]));
    expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])));

    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
    await tester.pumpAndSettle();
    expect(semantics, isNot(includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden])));
    expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden]));
    expect(semantics, includesNodeWith(label: 'Page #2'));
    expect(semantics, includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]));

    semantics.dispose();
  });
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

  testWidgets('PageView respects clipBehavior', (WidgetTester tester) async {
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: PageView(
          children: <Widget>[Container(height: 2000.0)],
        ),
      ),
    );

    // 1st, check that the render object has received the default clip behavior.
    final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first;
    expect(renderObject.clipBehavior, equals(Clip.hardEdge));

    // 2nd, check that the painting context has received the default clip behavior.
    final TestClipPaintingContext context = TestClipPaintingContext();
    renderObject.paint(context, Offset.zero);
    expect(context.clipBehavior, equals(Clip.hardEdge));

    // 3rd, pump a new widget to check that the render object can update its clip behavior.
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: PageView(
          clipBehavior: Clip.antiAlias,
1142
          children: <Widget>[Container(height: 2000.0)],
1143 1144 1145 1146 1147 1148 1149 1150 1151
        ),
      ),
    );
    expect(renderObject.clipBehavior, equals(Clip.antiAlias));

    // 4th, check that a non-default clip behavior can be sent to the painting context.
    renderObject.paint(context, Offset.zero);
    expect(context.clipBehavior, equals(Clip.antiAlias));
  });
1152 1153 1154 1155 1156 1157 1158

  testWidgets('PageView.padEnds tests', (WidgetTester tester) async {
    Finder viewportFinder() => find.byType(SliverFillViewport, skipOffstage: false);

    // PageView() defaults to true.
    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
1159
      child: PageView(),
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    ));

    expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, true);

    // PageView(padEnds: false) is propagated properly.
    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
      child: PageView(
        padEnds: false,
      ),
    ));

    expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, false);
  });
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

  testWidgets('PageView - precision error inside RenderSliverFixedExtentBoxAdaptor', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/95101

    final PageController controller = PageController(initialPage: 152);
    await tester.pumpWidget(
      Center(
        child: SizedBox(
          width: 392.72727272727275,
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: PageView.builder(
              controller: controller,
              itemCount: 366,
              itemBuilder: (BuildContext context, int index) {
                return const SizedBox();
              },
            ),
          ),
        ),
      ),
    );

    controller.jumpToPage(365);
    await tester.pump();
    expect(tester.takeException(), isNull);
  });
Adam Barth's avatar
Adam Barth committed
1201
}