page_view_test.dart 39.8 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/foundation.dart';
6
import 'package:flutter/gestures.dart' show DragStartBehavior;
7
import 'package:flutter/material.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter_test/flutter_test.dart';
Adam Barth's avatar
Adam Barth committed
10

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

void main() {
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 51
  // 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);
  });

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  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) { },
67
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
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 111
            ),
          ),
        ),
      );
    }

    // 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) { },
112
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
            ),
          ),
        ),
      );
    }

    // 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);
  });

137 138 139 140 141 142 143 144
  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);
145
    final MediaQueryData mediaQueryData = MediaQueryData.fromView(tester.binding.window);
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 175

    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);
  });

176 177 178 179 180 181
  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
182
  testWidgets('PageView control test', (WidgetTester tester) async {
183
    final List<String> log = <String>[];
Adam Barth's avatar
Adam Barth committed
184

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

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

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

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

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

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

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

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

    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();

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

    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);
242
    await tester.pumpAndSettle();
Adam Barth's avatar
Adam Barth committed
243 244 245 246 247

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

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

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

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

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

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

274
    // Easing overscroll past overscroll limit.
275 276 277 278 279 280
    if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) {
      await tester.drag(find.byType(PageView), const Offset(-500.0, 0.0));
    }
    else {
      await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0));
    }
281 282
    await tester.pump();

283
    expect(leftOf(0), lessThan(0.0));
284
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));
Dan Field's avatar
Dan Field committed
285
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
286 287

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

290
    await tester.pumpWidget(Directionality(
291
      textDirection: TextDirection.ltr,
292 293
      child: Center(
        child: SizedBox(
294 295
          width: 600.0,
          height: 400.0,
296
          child: PageView(
297
            controller: controller,
298
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
299
          ),
300 301 302 303 304 305
        ),
      ),
    ));

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

306
    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
307
    await tester.pumpAndSettle();
308 309 310

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

311
    await tester.pumpWidget(Directionality(
312
      textDirection: TextDirection.ltr,
313 314
      child: Center(
        child: SizedBox(
315 316
          width: 300.0,
          height: 400.0,
317
          child: PageView(
318
            controller: controller,
319
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
320
          ),
321 322 323 324 325 326
        ),
      ),
    ));

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

327
    controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
328
    await tester.pumpAndSettle();
329 330 331 332 333

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

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

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

349
    await tester.drag(find.byType(PageView), const Offset(-1250.0, 0.0));
350
    await tester.pumpAndSettle();
351 352 353

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

354
    await tester.pumpWidget(Directionality(
355
      textDirection: TextDirection.ltr,
356 357
      child: Center(
        child: SizedBox(
358 359
          width: 250.0,
          height: 100.0,
360 361
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
362
          ),
363 364 365 366 367 368
        ),
      ),
    ));

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

369
    await tester.pumpWidget(Directionality(
370
      textDirection: TextDirection.ltr,
371 372
      child: Center(
        child: SizedBox(
373 374
          width: 450.0,
          height: 400.0,
375 376
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
377
          ),
378 379 380 381 382 383
        ),
      ),
    ));

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

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

    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);
  });

417
  testWidgets('PageView in zero-size container', (WidgetTester tester) async {
418
    await tester.pumpWidget(Directionality(
419
      textDirection: TextDirection.ltr,
420
      child: Center(
421
        child: SizedBox.shrink(
422 423
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
424
          ),
425 426 427 428
        ),
      ),
    ));

429
    expect(find.text('Alabama', skipOffstage: false), findsOneWidget);
430

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

    expect(find.text('Alabama'), findsOneWidget);
445
  });
446 447 448

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

    expect(log, isEmpty);

459
    final TestGesture gesture =
460
        await tester.startGesture(const Offset(100.0, 100.0));
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    // 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();
489
    await tester.pumpAndSettle();
490 491 492 493 494 495 496

    expect(log, isEmpty);

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

497 498
  testWidgets('Bouncing scroll physics ballistics does not overshoot', (WidgetTester tester) async {
    final List<int> log = <int>[];
499
    final PageController controller = PageController(viewportFraction: 0.9);
500

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

      if (size != null) {
513
        return OverflowBox(
514 515 516 517
          minWidth: size.width,
          minHeight: size.height,
          maxWidth: size.width,
          maxHeight: size.height,
518
          child: pageView,
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 547 548 549 550
        );
      } 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);
  });

551
  testWidgets('PageView viewportFraction', (WidgetTester tester) async {
552
    PageController controller = PageController(viewportFraction: 7/8);
553 554

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

    await tester.pumpWidget(build(controller));

575 576
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(50.0, 0.0));
    expect(tester.getTopLeft(find.text('Alaska')), const Offset(750.0, 0.0));
577 578 579 580

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

581 582 583
    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));
584

585
    controller = PageController(viewportFraction: 39/40);
586 587 588

    await tester.pumpWidget(build(controller));

589 590 591
    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));
592 593
  });

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

597
    Widget build({ required bool pageSnapping }) {
598
      return Directionality(
599
        textDirection: TextDirection.ltr,
600
        child: PageView(
601 602 603
          pageSnapping: pageSnapping,
          onPageChanged: log.add,
          children:
604
              kStates.map<Widget>((String state) => Text(state)).toList(),
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 653 654 655 656
        ),
      );
    }

    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);
  });

657
  testWidgets('PageView small viewportFraction', (WidgetTester tester) async {
658
    final PageController controller = PageController(viewportFraction: 1/8);
659 660

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

    await tester.pumpWidget(build(controller));

681 682 683 684 685
    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));
686 687 688 689

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

690 691 692 693 694 695 696 697 698
    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));
699 700 701
  });

  testWidgets('PageView large viewportFraction', (WidgetTester tester) async {
702
    final PageController controller = PageController(viewportFraction: 5/4);
703 704

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

    await tester.pumpWidget(build(controller));

725 726
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100.0, 0.0));
    expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0));
727 728 729 730

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

731
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-100.0, 0.0));
732
  });
733

734 735 736 737 738 739 740 741 742 743 744 745
  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,
746
                color: index.isEven
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
                  ? 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));
768 769
    },
  );
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  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,
786
                color: index.isEven
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
                  ? 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));
805 806
    },
  );
807 808 809 810 811

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

      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.
835
      for (final int index in visiblePages) {
836 837 838 839 840 841 842 843 844 845 846 847
        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];
848
      for (final int index in visiblePages) {
849 850 851 852
        expect(find.text('$index'), findsOneWidget);
        await tester.tap(find.text('$index'));
        expect(tappedIndex, index);
      }
853 854
    },
  );
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
  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,
871
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
              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();
  });

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

    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);
  });
923

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

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

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

1007 1008
    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
1009
      textDirection: TextDirection.ltr,
1010
      child: PageView(
1011
          controller: controller,
1012 1013
          children: List<Widget>.generate(3, (int i) {
            return Semantics(
1014
              container: true,
1015
              child: Text('Page #$i'),
1016
            );
1017
          }),
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        ),
    ));
    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();
  });
1042 1043

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

  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,
1070
            child: Text('Page #$i'),
1071 1072 1073 1074 1075 1076 1077 1078
          );
        }),
      ),
    ));
    // Simulate precision error.
    pageController.position.jumpTo(799.99999999999);
    expect(pageController.page, 1);
  });
1079 1080 1081 1082 1083 1084 1085 1086 1087

  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,
1088
          allowImplicitScrolling: true,
1089 1090 1091
          children: List<Widget>.generate(4, (int i) {
            return Semantics(
              container: true,
1092
              child: Text('Page #$i'),
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
            );
          }),
        ),
    ));
    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();
  });
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

  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,
1147
          children: <Widget>[Container(height: 2000.0)],
1148 1149 1150 1151 1152 1153 1154 1155 1156
        ),
      ),
    );
    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));
  });
1157 1158 1159 1160 1161 1162 1163

  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,
1164
      child: PageView(),
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    ));

    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);
  });
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

  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
1206
}