page_view_test.dart 32.7 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 6
// @dart = 2.8

Adam Barth's avatar
Adam Barth committed
7
import 'package:flutter_test/flutter_test.dart';
8
import 'package:flutter/material.dart';
9
import 'package:flutter/rendering.dart';
Adam Barth's avatar
Adam Barth committed
10
import 'package:flutter/widgets.dart';
11
import 'package:flutter/gestures.dart' show DragStartBehavior;
Adam Barth's avatar
Adam Barth committed
12

13
import '../rendering/rendering_tester.dart';
14
import 'semantics_tester.dart';
Adam Barth's avatar
Adam Barth committed
15 16
import 'states.dart';

17
const Duration _frameDuration = Duration(milliseconds: 100);
Adam Barth's avatar
Adam Barth committed
18 19 20

void main() {
  testWidgets('PageView control test', (WidgetTester tester) async {
21
    final List<String> log = <String>[];
Adam Barth's avatar
Adam Barth committed
22

23
    await tester.pumpWidget(Directionality(
24
      textDirection: TextDirection.ltr,
25
      child: PageView(
26
        dragStartBehavior: DragStartBehavior.down,
27
        children: kStates.map<Widget>((String state) {
28
          return GestureDetector(
29
            dragStartBehavior: DragStartBehavior.down,
30 31 32
            onTap: () {
              log.add(state);
            },
33
            child: Container(
34 35
              height: 200.0,
              color: const Color(0xFF0000FF),
36
              child: Text(state),
37 38 39 40
            ),
          );
        }).toList(),
      ),
Adam Barth's avatar
Adam Barth committed
41 42 43 44 45 46 47 48
    ));

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

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

49
    await tester.drag(find.byType(PageView), const Offset(-20.0, 0.0));
Adam Barth's avatar
Adam Barth committed
50 51 52 53 54 55
    await tester.pump();

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

56
    await tester.pumpAndSettle(_frameDuration);
Adam Barth's avatar
Adam Barth committed
57 58 59 60

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

61 62
    await tester.drag(find.byType(PageView), const Offset(-401.0, 0.0));
    await tester.pumpAndSettle(_frameDuration);
Adam Barth's avatar
Adam Barth committed
63 64 65 66 67 68 69 70 71

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

72
    await tester.fling(find.byType(PageView), const Offset(-200.0, 0.0), 1000.0);
73
    await tester.pumpAndSettle(_frameDuration);
Adam Barth's avatar
Adam Barth committed
74 75 76 77 78 79

    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);
80
    await tester.pumpAndSettle(_frameDuration);
Adam Barth's avatar
Adam Barth committed
81 82 83 84 85

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

87
  testWidgets('PageView does not squish when overscrolled', (WidgetTester tester) async {
88 89 90 91 92
    await tester.pumpWidget(MaterialApp(
      home: PageView(
        children: List<Widget>.generate(10, (int i) {
          return Container(
            key: ValueKey<int>(i),
93
            color: const Color(0xFF0000FF),
94 95 96 97 98
          );
        }),
      ),
    ));

99 100
    Size sizeOf(int i) => tester.getSize(find.byKey(ValueKey<int>(i)));
    double leftOf(int i) => tester.getTopLeft(find.byKey(ValueKey<int>(i))).dx;
101 102 103 104

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

105
    // Going into overscroll.
106
    await tester.drag(find.byType(PageView), const Offset(100.0, 0.0));
107 108
    await tester.pump();

109
    expect(leftOf(0), greaterThan(0.0));
110 111
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));

112
    // Easing overscroll past overscroll limit.
113
    await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0));
114 115
    await tester.pump();

116
    expect(leftOf(0), lessThan(0.0));
117
    expect(sizeOf(0), equals(const Size(800.0, 600.0)));
Dan Field's avatar
Dan Field committed
118
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
119 120

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

123
    await tester.pumpWidget(Directionality(
124
      textDirection: TextDirection.ltr,
125 126
      child: Center(
        child: SizedBox(
127 128
          width: 600.0,
          height: 400.0,
129
          child: PageView(
130
            controller: controller,
131
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
132
          ),
133 134 135 136 137 138
        ),
      ),
    ));

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

139 140
    controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
    await tester.pumpAndSettle(const Duration(milliseconds: 100));
141 142 143

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

144
    await tester.pumpWidget(Directionality(
145
      textDirection: TextDirection.ltr,
146 147
      child: Center(
        child: SizedBox(
148 149
          width: 300.0,
          height: 400.0,
150
          child: PageView(
151
            controller: controller,
152
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
153
          ),
154 155 156 157 158 159
        ),
      ),
    ));

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

160 161
    controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease);
    await tester.pumpAndSettle(const Duration(milliseconds: 100));
162 163 164 165 166

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

  testWidgets('PageController page stability', (WidgetTester tester) async {
167
    await tester.pumpWidget(Directionality(
168
      textDirection: TextDirection.ltr,
169 170
      child: Center(
        child: SizedBox(
171 172
          width: 600.0,
          height: 400.0,
173 174
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
175
          ),
176
        ),
177 178 179 180 181
      ),
    ));

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

182 183
    await tester.drag(find.byType(PageView), const Offset(-1250.0, 0.0));
    await tester.pumpAndSettle(const Duration(milliseconds: 100));
184 185 186

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

187
    await tester.pumpWidget(Directionality(
188
      textDirection: TextDirection.ltr,
189 190
      child: Center(
        child: SizedBox(
191 192
          width: 250.0,
          height: 100.0,
193 194
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
195
          ),
196 197 198 199 200 201
        ),
      ),
    ));

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

202
    await tester.pumpWidget(Directionality(
203
      textDirection: TextDirection.ltr,
204 205
      child: Center(
        child: SizedBox(
206 207
          width: 450.0,
          height: 400.0,
208 209
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
210
          ),
211 212 213 214 215 216
        ),
      ),
    ));

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

218
  testWidgets('PageController nextPage and previousPage return Futures that resolve', (WidgetTester tester) async {
219 220
    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
221
        textDirection: TextDirection.ltr,
222
        child: PageView(
223
          controller: controller,
224
          children: kStates.map<Widget>((String state) => Text(state)).toList(),
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        ),
    ));

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

250
  testWidgets('PageView in zero-size container', (WidgetTester tester) async {
251
    await tester.pumpWidget(Directionality(
252
      textDirection: TextDirection.ltr,
253 254
      child: Center(
        child: SizedBox(
255 256
          width: 0.0,
          height: 0.0,
257 258
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
259
          ),
260 261 262 263
        ),
      ),
    ));

264
    expect(find.text('Alabama', skipOffstage: false), findsOneWidget);
265

266
    await tester.pumpWidget(Directionality(
267
      textDirection: TextDirection.ltr,
268 269
      child: Center(
        child: SizedBox(
270 271
          width: 200.0,
          height: 200.0,
272 273
          child: PageView(
            children: kStates.map<Widget>((String state) => Text(state)).toList(),
274
          ),
275 276 277 278 279
        ),
      ),
    ));

    expect(find.text('Alabama'), findsOneWidget);
280
  });
281 282 283

  testWidgets('Page changes at halfway point', (WidgetTester tester) async {
    final List<int> log = <int>[];
284
    await tester.pumpWidget(Directionality(
285
      textDirection: TextDirection.ltr,
286
      child: PageView(
287
        onPageChanged: log.add,
288
        children: kStates.map<Widget>((String state) => Text(state)).toList(),
289
      ),
290 291 292 293
    ));

    expect(log, isEmpty);

294
    final TestGesture gesture =
295
        await tester.startGesture(const Offset(100.0, 100.0));
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    // 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();
324
    await tester.pumpAndSettle();
325 326 327 328 329 330 331

    expect(log, isEmpty);

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

332 333
  testWidgets('Bouncing scroll physics ballistics does not overshoot', (WidgetTester tester) async {
    final List<int> log = <int>[];
334
    final PageController controller = PageController(viewportFraction: 0.9);
335

336
    Widget build(PageController controller, { Size size }) {
337
      final Widget pageView = Directionality(
338
        textDirection: TextDirection.ltr,
339
        child: PageView(
340 341 342
          controller: controller,
          onPageChanged: log.add,
          physics: const BouncingScrollPhysics(),
343
          children: kStates.map<Widget>((String state) => Text(state)).toList(),
344 345 346 347
        ),
      );

      if (size != null) {
348
        return OverflowBox(
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
          child: pageView,
          minWidth: size.width,
          minHeight: size.height,
          maxWidth: size.width,
          maxHeight: size.height,
        );
      } 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);
  });

386
  testWidgets('PageView viewportFraction', (WidgetTester tester) async {
387
    PageController controller = PageController(viewportFraction: 7/8);
388 389

    Widget build(PageController controller) {
390
      return Directionality(
391
        textDirection: TextDirection.ltr,
392
        child: PageView.builder(
393 394 395
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
396
            return Container(
397 398
              height: 200.0,
              color: index % 2 == 0
399 400
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
401
              child: Text(kStates[index]),
402 403 404
            );
          },
        ),
405 406 407 408 409
      );
    }

    await tester.pumpWidget(build(controller));

410 411
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(50.0, 0.0));
    expect(tester.getTopLeft(find.text('Alaska')), const Offset(750.0, 0.0));
412 413 414 415

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

416 417 418
    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));
419

420
    controller = PageController(viewportFraction: 39/40);
421 422 423

    await tester.pumpWidget(build(controller));

424 425 426
    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));
427 428
  });

429 430 431 432
  testWidgets('Page snapping disable and reenable', (WidgetTester tester) async {
    final List<int> log = <int>[];

    Widget build({ bool pageSnapping }) {
433
      return Directionality(
434
        textDirection: TextDirection.ltr,
435
        child: PageView(
436 437 438
          pageSnapping: pageSnapping,
          onPageChanged: log.add,
          children:
439
              kStates.map<Widget>((String state) => Text(state)).toList(),
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 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 485 486 487 488 489 490 491
        ),
      );
    }

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

492
  testWidgets('PageView small viewportFraction', (WidgetTester tester) async {
493
    final PageController controller = PageController(viewportFraction: 1/8);
494 495

    Widget build(PageController controller) {
496
      return Directionality(
497
        textDirection: TextDirection.ltr,
498
        child: PageView.builder(
499 500 501
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
502
            return Container(
503 504
              height: 200.0,
              color: index % 2 == 0
505 506
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
507
              child: Text(kStates[index]),
508 509 510
            );
          },
        ),
511 512 513 514 515
      );
    }

    await tester.pumpWidget(build(controller));

516 517 518 519 520
    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));
521 522 523 524

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

525 526 527 528 529 530 531 532 533
    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));
534 535 536
  });

  testWidgets('PageView large viewportFraction', (WidgetTester tester) async {
537
    final PageController controller = PageController(viewportFraction: 5/4);
538 539

    Widget build(PageController controller) {
540
      return Directionality(
541
        textDirection: TextDirection.ltr,
542
        child: PageView.builder(
543 544 545
          controller: controller,
          itemCount: kStates.length,
          itemBuilder: (BuildContext context, int index) {
546
            return Container(
547 548
              height: 200.0,
              color: index % 2 == 0
549 550
                ? const Color(0xFF0000FF)
                : const Color(0xFF00FF00),
551
              child: Text(kStates[index]),
552 553 554
            );
          },
        ),
555 556 557 558 559
      );
    }

    await tester.pumpWidget(build(controller));

560 561
    expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100.0, 0.0));
    expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0));
562 563 564 565

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

566
    expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-100.0, 0.0));
567
  });
568

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
  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,
                color: index % 2 == 0
                  ? 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));
  });

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 657 658 659 660 661 662 663 664 665 666 667
  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,
                color: index % 2 == 0
                  ? 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));
  });

  testWidgets(
    'All visible pages are able to receive touch events',
    (WidgetTester tester) async {
      // Regression test for https://github.com/flutter/flutter/issues/23873.
      final PageController controller = PageController(viewportFraction: 1/4, initialPage: 0);
      int tappedIndex;

      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.
668
      for (final int index in visiblePages) {
669 670 671 672 673 674 675 676 677 678 679 680
        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];
681
      for (final int index in visiblePages) {
682 683 684 685 686 687
        expect(find.text('$index'), findsOneWidget);
        await tester.tap(find.text('$index'));
        expect(tappedIndex, index);
      }
  });

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  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(
              children: kStates.map<Widget>((String state) => Text(state)).toList(),
              controller: controller,
              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();
  });

730
  testWidgets('PageView does not report page changed on overscroll', (WidgetTester tester) async {
731
    final PageController controller = PageController(
732 733
      initialPage: kStates.length - 1,
    );
734 735
    int changeIndex = 0;
    Widget build() {
736
      return Directionality(
737
        textDirection: TextDirection.ltr,
738
        child: PageView(
739
          children:
740
              kStates.map<Widget>((String state) => Text(state)).toList(),
741 742 743 744 745
          controller: controller,
          onPageChanged: (int page) {
            changeIndex = page;
          },
        ),
746 747 748 749 750 751 752 753 754 755
      );
    }

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

757
  testWidgets('PageView can restore page', (WidgetTester tester) async {
758
    final PageController controller = PageController();
759 760 761 762 763 764 765 766 767
    try {
      controller.page;
      fail('Accessing page before attaching should fail.');
    } on AssertionError catch (e) {
      expect(
        e.message,
        'PageController.page cannot be accessed before a PageView is built with it.',
      );
    }
768 769
    final PageStorageBucket bucket = PageStorageBucket();
    await tester.pumpWidget(Directionality(
770
      textDirection: TextDirection.ltr,
771
      child: PageStorage(
772
        bucket: bucket,
773
        child: PageView(
774
          key: const PageStorageKey<String>('PageView'),
775
          controller: controller,
776
          children: const <Widget>[
777 778 779
            Placeholder(),
            Placeholder(),
            Placeholder(),
780 781 782
          ],
        ),
      ),
783
    ));
784 785 786 787 788
    expect(controller.page, 0);
    controller.jumpToPage(2);
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 1);
    expect(controller.page, 2);
    await tester.pumpWidget(
789
      PageStorage(
790
        bucket: bucket,
791
        child: Container(),
792 793
      ),
    );
794 795 796 797 798 799 800 801 802
    try {
      controller.page;
      fail('Accessing page after detaching all PageViews should fail.');
    } on AssertionError catch (e) {
      expect(
        e.message,
        'PageController.page cannot be accessed before a PageView is built with it.',
      );
    }
803
    await tester.pumpWidget(Directionality(
804
      textDirection: TextDirection.ltr,
805
      child: PageStorage(
806
        bucket: bucket,
807
        child: PageView(
808
          key: const PageStorageKey<String>('PageView'),
809
          controller: controller,
810
          children: const <Widget>[
811 812 813
            Placeholder(),
            Placeholder(),
            Placeholder(),
814 815 816
          ],
        ),
      ),
817
    ));
818
    expect(controller.page, 2);
819

820 821
    final PageController controller2 = PageController(keepPage: false);
    await tester.pumpWidget(Directionality(
822
      textDirection: TextDirection.ltr,
823
      child: PageStorage(
824
        bucket: bucket,
825
        child: PageView(
826
          key: const PageStorageKey<String>('Check it again against your list and see consistency!'),
827
          controller: controller2,
828
          children: const <Widget>[
829 830 831
            Placeholder(),
            Placeholder(),
            Placeholder(),
832 833 834
          ],
        ),
      ),
835
    ));
836
    expect(controller2.page, 0);
837
  });
838 839

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

842 843
    final PageController controller = PageController();
    await tester.pumpWidget(Directionality(
844
      textDirection: TextDirection.ltr,
845
      child: PageView(
846
          controller: controller,
847 848 849
          children: List<Widget>.generate(3, (int i) {
            return Semantics(
              child: Text('Page #$i'),
850 851
              container: true,
            );
852
          }),
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        ),
    ));
    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();
  });
877 878

  testWidgets('PageMetrics', (WidgetTester tester) async {
879
    final PageMetrics page = PageMetrics(
880 881 882 883 884 885 886 887 888 889 890 891 892
      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);
  });
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

  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(
            child: Text('Page #$i'),
            container: true,
          );
        }),
      ),
    ));
    // Simulate precision error.
    pageController.position.jumpTo(799.99999999999);
    expect(pageController.page, 1);
  });
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

  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,
          children: List<Widget>.generate(4, (int i) {
            return Semantics(
              child: Text('Page #$i'),
              container: true,
            );
          }),
          allowImplicitScrolling: true,
        ),
    ));
    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();
  });
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

  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(
          children: <Widget>[Container(height: 2000.0)],
          clipBehavior: Clip.antiAlias,
        ),
      ),
    );
    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));
  });
Adam Barth's avatar
Adam Barth committed
991
}