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

import 'package:flutter/material.dart';
6
import 'package:flutter/services.dart';
Ian Hickson's avatar
Ian Hickson committed
7 8
import 'package:flutter_test/flutter_test.dart';

9
import '../rendering/mock_canvas.dart';
10

Ian Hickson's avatar
Ian Hickson committed
11
void main() {
12
  TestWidgetsFlutterBinding.ensureInitialized();
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
  late DateTime firstDate;
  late DateTime lastDate;
  late DateTime initialDate;
  late DateTime today;
  late SelectableDayPredicate? selectableDayPredicate;
  late DatePickerEntryMode initialEntryMode;
  late DatePickerMode initialCalendarMode;

  String? cancelText;
  String? confirmText;
  String? errorFormatText;
  String? errorInvalidText;
  String? fieldHintText;
  String? fieldLabelText;
  String? helpText;
29

30 31
  final Finder nextMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Next month') ?? false));
  final Finder previousMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Previous month') ?? false));
32 33 34 35 36 37
  final Finder switchToInputIcon = find.byIcon(Icons.edit);
  final Finder switchToCalendarIcon = find.byIcon(Icons.calendar_today);

  TextField textField(WidgetTester tester) {
    return tester.widget<TextField>(find.byType(TextField));
  }
38

39
  setUp(() {
40
    firstDate = DateTime(2001);
41 42
    lastDate = DateTime(2031, DateTime.december, 31);
    initialDate = DateTime(2016, DateTime.january, 15);
43
    today = DateTime(2016, DateTime.january, 3);
44
    selectableDayPredicate = null;
45 46 47 48 49 50 51 52 53 54
    initialEntryMode = DatePickerEntryMode.calendar;
    initialCalendarMode = DatePickerMode.day;

    cancelText = null;
    confirmText = null;
    errorFormatText = null;
    errorInvalidText = null;
    fieldHintText = null;
    fieldLabelText = null;
    helpText = null;
55
  });
Ian Hickson's avatar
Ian Hickson committed
56

57 58
  Future<void> prepareDatePicker(
    WidgetTester tester,
59 60 61
    Future<void> Function(Future<DateTime?> date) callback, {
    TextDirection textDirection = TextDirection.ltr,
  }) async {
62
    late BuildContext buttonContext;
63 64 65
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: Builder(
66
          builder: (BuildContext context) {
67
            return ElevatedButton(
68 69 70
              onPressed: () {
                buttonContext = context;
              },
71
              child: const Text('Go'),
72 73 74 75 76 77 78 79 80
            );
          },
        ),
      ),
    ));

    await tester.tap(find.text('Go'));
    expect(buttonContext, isNotNull);

81
    final Future<DateTime?> date = showDatePicker(
82 83 84 85
      context: buttonContext,
      initialDate: initialDate,
      firstDate: firstDate,
      lastDate: lastDate,
86
      currentDate: today,
87 88 89 90 91 92 93 94 95 96
      selectableDayPredicate: selectableDayPredicate,
      initialDatePickerMode: initialCalendarMode,
      initialEntryMode: initialEntryMode,
      cancelText: cancelText,
      confirmText: confirmText,
      errorFormatText: errorFormatText,
      errorInvalidText: errorInvalidText,
      fieldHintText: fieldHintText,
      fieldLabelText: fieldLabelText,
      helpText: helpText,
97
      builder: (BuildContext context, Widget? child) {
98 99
        return Directionality(
          textDirection: textDirection,
100
          child: child ?? const SizedBox(),
101 102
        );
      },
103
    );
104

105
    await tester.pumpAndSettle(const Duration(seconds: 1));
106 107 108
    await callback(date);
  }

109 110 111 112 113
  group('showDatePicker Dialog', () {
    testWidgets('Cancel, confirm, and help text is used', (WidgetTester tester) async {
      cancelText = 'nope';
      confirmText = 'yep';
      helpText = 'help';
114
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
115 116 117
        expect(find.text(cancelText!), findsOneWidget);
        expect(find.text(confirmText!), findsOneWidget);
        expect(find.text(helpText!), findsOneWidget);
118
      });
119 120
    });

121
    testWidgets('Initial date is the default', (WidgetTester tester) async {
122
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
123 124 125
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.january, 15));
      });
126 127
    });

128
    testWidgets('Can cancel', (WidgetTester tester) async {
129
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
130 131 132
        await tester.tap(find.text('CANCEL'));
        expect(await date, isNull);
      });
133 134
    });

135
    testWidgets('Can switch from calendar to input entry mode', (WidgetTester tester) async {
136
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
137 138 139 140 141
        expect(find.byType(TextField), findsNothing);
        await tester.tap(find.byIcon(Icons.edit));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsOneWidget);
      });
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
    testWidgets('Can switch from input to calendar entry mode', (WidgetTester tester) async {
      initialEntryMode = DatePickerEntryMode.input;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.byType(TextField), findsOneWidget);
        await tester.tap(find.byIcon(Icons.calendar_today));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsNothing);
      });
    });

    testWidgets('Can not switch out of calendarOnly mode', (WidgetTester tester) async {
      initialEntryMode = DatePickerEntryMode.calendarOnly;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.byType(TextField), findsNothing);
        expect(find.byIcon(Icons.edit), findsNothing);
      });
    });

    testWidgets('Can not switch out of inputOnly mode', (WidgetTester tester) async {
      initialEntryMode = DatePickerEntryMode.inputOnly;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.byType(TextField), findsOneWidget);
        expect(find.byIcon(Icons.calendar_today), findsNothing);
      });
    });

    testWidgets('Switching to input mode keeps selected date', (WidgetTester tester) async {
171
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
172 173 174 175 176 177
        await tester.tap(find.text('12'));
        await tester.tap(find.byIcon(Icons.edit));
        await tester.pumpAndSettle();
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.january, 12));
      });
178 179
    });

180 181 182 183 184 185 186 187 188 189 190
    testWidgets('Input only mode should validate date', (WidgetTester tester) async {
      initialEntryMode = DatePickerEntryMode.inputOnly;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        // Enter text input mode and type an invalid date to get error.
        await tester.enterText(find.byType(TextField), '1234567');
        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
        expect(find.text('Invalid format.'), findsOneWidget);
      });
    });

191
    testWidgets('Switching to input mode resets input error state', (WidgetTester tester) async {
192
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
193 194 195 196 197 198 199 200
        // Enter text input mode and type an invalid date to get error.
        await tester.tap(find.byIcon(Icons.edit));
        await tester.pumpAndSettle();
        await tester.enterText(find.byType(TextField), '1234567');
        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
        expect(find.text('Invalid format.'), findsOneWidget);

201
        // Toggle to calendar mode and then back to input mode
202 203 204 205 206 207 208 209 210 211 212 213 214
        await tester.tap(find.byIcon(Icons.calendar_today));
        await tester.pumpAndSettle();
        await tester.tap(find.byIcon(Icons.edit));
        await tester.pumpAndSettle();
        expect(find.text('Invalid format.'), findsNothing);

        // Edit the text, the error should not be showing until ok is tapped
        await tester.enterText(find.byType(TextField), '1234567');
        await tester.pumpAndSettle();
        expect(find.text('Invalid format.'), findsNothing);
      });
    });

215 216 217 218 219 220 221
    testWidgets('builder parameter', (WidgetTester tester) async {
      Widget buildFrame(TextDirection textDirection) {
        return MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
222
                  return ElevatedButton(
223 224 225 226 227 228 229
                    child: const Text('X'),
                    onPressed: () {
                      showDatePicker(
                        context: context,
                        initialDate: DateTime.now(),
                        firstDate: DateTime(2018),
                        lastDate: DateTime(2030),
230
                        builder: (BuildContext context, Widget? child) {
231 232
                          return Directionality(
                            textDirection: textDirection,
233
                            child: child ?? const SizedBox(),
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
                          );
                        },
                      );
                    },
                  );
                },
              ),
            ),
          ),
        );
      }

      await tester.pumpWidget(buildFrame(TextDirection.ltr));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      final double ltrOkRight = tester.getBottomRight(find.text('OK')).dx;

      await tester.tap(find.text('OK')); // Dismiss the dialog.
      await tester.pumpAndSettle();

      await tester.pumpWidget(buildFrame(TextDirection.rtl));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();

      // Verify that the time picker is being laid out RTL.
      // We expect the left edge of the 'OK' button in the RTL
      // layout to match the gap between right edge of the 'OK'
      // button and the right edge of the 800 wide window.
      expect(tester.getBottomLeft(find.text('OK')).dx, 800 - ltrOkRight);
263 264
    });

265 266 267 268 269 270 271 272 273 274 275
    testWidgets('uses nested navigator if useRootNavigator is false', (WidgetTester tester) async {
      final _DatePickerObserver rootObserver = _DatePickerObserver();
      final _DatePickerObserver nestedObserver = _DatePickerObserver();

      await tester.pumpWidget(MaterialApp(
        navigatorObservers: <NavigatorObserver>[rootObserver],
        home: Navigator(
          observers: <NavigatorObserver>[nestedObserver],
          onGenerateRoute: (RouteSettings settings) {
            return MaterialPageRoute<dynamic>(
              builder: (BuildContext context) {
276
                return ElevatedButton(
277 278 279 280 281 282 283
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      useRootNavigator: false,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
284
                      builder: (BuildContext context, Widget? child) => const SizedBox(),
285 286 287 288 289 290 291 292 293 294 295
                    );
                  },
                  child: const Text('Show Date Picker'),
                );
              },
            );
          },
        ),
      ));

      // Open the dialog.
296
      await tester.tap(find.byType(ElevatedButton));
297 298 299

      expect(rootObserver.datePickerCount, 0);
      expect(nestedObserver.datePickerCount, 1);
300
    });
301

302 303 304 305
    testWidgets('honors DialogTheme for shape and elevation', (WidgetTester tester) async {
      // Test that the defaults work
      const DialogTheme datePickerDefaultDialogTheme = DialogTheme(
        shape: RoundedRectangleBorder(
306
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
307 308 309 310 311 312 313 314
        ),
        elevation: 24,
      );
      await tester.pumpWidget(
        MaterialApp(
          home: Center(
            child: Builder(
              builder: (BuildContext context) {
315
                return ElevatedButton(
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                  child: const Text('X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
                    );
                  },
                );
              },
            ),
          ),
        ),
      );
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      final Material defaultDialogMaterial = tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first);
      expect(defaultDialogMaterial.shape, datePickerDefaultDialogTheme.shape);
      expect(defaultDialogMaterial.elevation, datePickerDefaultDialogTheme.elevation);

      // Test that it honors ThemeData.dialogTheme settings
      const DialogTheme customDialogTheme = DialogTheme(
        shape: RoundedRectangleBorder(
340
          borderRadius: BorderRadius.all(Radius.circular(40.0)),
341 342 343 344 345 346 347 348 349
        ),
        elevation: 50,
      );
      await tester.pumpWidget(
        MaterialApp(
          theme: ThemeData.fallback().copyWith(dialogTheme: customDialogTheme),
          home: Center(
            child: Builder(
              builder: (BuildContext context) {
350
                return ElevatedButton(
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
                  child: const Text('X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
                    );
                  },
                );
              },
            ),
          ),
        ),
      );
366 367
      await tester.pump(); // start theme animation
      await tester.pump(const Duration(seconds: 5)); // end theme animation
368 369 370 371 372
      final Material themeDialogMaterial = tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first);
      expect(themeDialogMaterial.shape, customDialogTheme.shape);
      expect(themeDialogMaterial.elevation, customDialogTheme.elevation);
    });

373 374 375 376 377 378 379 380 381 382 383 384 385
    testWidgets('OK Cancel button layout', (WidgetTester tester) async {
       Widget buildFrame(TextDirection textDirection) {
         return MaterialApp(
           home: Material(
             child: Center(
               child: Builder(
                 builder: (BuildContext context) {
                   return ElevatedButton(
                     child: const Text('X'),
                     onPressed: () {
                       showDatePicker(
                         context: context,
                         initialDate: DateTime(2016, DateTime.january, 15),
386
                         firstDate:DateTime(2001),
387
                         lastDate: DateTime(2031, DateTime.december, 31),
388
                         builder: (BuildContext context, Widget? child) {
389 390
                           return Directionality(
                             textDirection: textDirection,
391
                             child: child ?? const SizedBox(),
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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
                           );
                         },
                       );
                     },
                   );
                 },
               ),
             ),
           ),
         );
       }

      // Default landscape layout.

      await tester.pumpWidget(buildFrame(TextDirection.ltr));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      expect(tester.getBottomRight(find.text('OK')).dx, 622);
      expect(tester.getBottomLeft(find.text('OK')).dx, 594);
      expect(tester.getBottomRight(find.text('CANCEL')).dx, 560);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(buildFrame(TextDirection.rtl));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      expect(tester.getBottomRight(find.text('OK')).dx, 206);
      expect(tester.getBottomLeft(find.text('OK')).dx, 178);
      expect(tester.getBottomRight(find.text('CANCEL')).dx, 324);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      // Portrait layout.

      addTearDown(tester.binding.window.clearPhysicalSizeTestValue);
      tester.binding.window.physicalSizeTestValue = const Size(900, 1200);

      await tester.pumpWidget(buildFrame(TextDirection.ltr));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      expect(tester.getBottomRight(find.text('OK')).dx, 258);
      expect(tester.getBottomLeft(find.text('OK')).dx, 230);
      expect(tester.getBottomRight(find.text('CANCEL')).dx, 196);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(buildFrame(TextDirection.rtl));
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
      expect(tester.getBottomRight(find.text('OK')).dx, 70);
      expect(tester.getBottomLeft(find.text('OK')).dx, 42);
      expect(tester.getBottomRight(find.text('CANCEL')).dx, 188);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();
    });
447
  });
448

449 450
  group('Calendar mode', () {
    testWidgets('Can select a day', (WidgetTester tester) async {
451
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
452 453 454 455
        await tester.tap(find.text('12'));
        await tester.tap(find.text('OK'));
        expect(await date, equals(DateTime(2016, DateTime.january, 12)));
      });
456 457
    });

458
    testWidgets('Can select a month', (WidgetTester tester) async {
459
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
460 461 462 463 464 465
        await tester.tap(previousMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        await tester.tap(find.text('25'));
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2015, DateTime.december, 25));
      });
466 467
    });

468
    testWidgets('Can select a year', (WidgetTester tester) async {
469
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
470 471 472 473 474 475
        await tester.tap(find.text('January 2016')); // Switch to year mode.
        await tester.pump();
        await tester.tap(find.text('2018'));
        await tester.pump();
        expect(find.text('January 2018'), findsOneWidget);
      });
476
    });
477

478 479
    testWidgets('Selecting date does not change displayed month', (WidgetTester tester) async {
      initialDate = DateTime(2020, DateTime.march, 15);
480
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
481 482 483 484 485 486 487 488 489 490 491
        await tester.tap(nextMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        expect(find.text('April 2020'), findsOneWidget);
        await tester.tap(find.text('25'));
        await tester.pumpAndSettle();
        expect(find.text('April 2020'), findsOneWidget);
        // There isn't a 31 in April so there shouldn't be one if it is showing April
        expect(find.text('31'), findsNothing);
      });
    });

492
    testWidgets('Changing year does not change selected date', (WidgetTester tester) async {
493
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
494 495 496 497 498 499 500
        await tester.tap(find.text('January 2016'));
        await tester.pump();
        await tester.tap(find.text('2018'));
        await tester.pump();
        await tester.tap(find.text('OK'));
        expect(await date, equals(DateTime(2016, DateTime.january, 15)));
      });
501 502
    });

503
    testWidgets('Changing year does not change the month', (WidgetTester tester) async {
504
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
505 506 507 508 509 510 511 512 513 514 515 516 517
        await tester.tap(nextMonthIcon);
        await tester.pumpAndSettle();
        await tester.tap(nextMonthIcon);
        await tester.pumpAndSettle();
        await tester.tap(find.text('March 2016'));
        await tester.pumpAndSettle();
        await tester.tap(find.text('2018'));
        await tester.pumpAndSettle();
        expect(find.text('March 2018'), findsOneWidget);
      });
    });

    testWidgets('Can select a year and then a day', (WidgetTester tester) async {
518
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
519 520 521 522 523 524 525 526 527 528 529
        await tester.tap(find.text('January 2016')); // Switch to year mode.
        await tester.pump();
        await tester.tap(find.text('2017'));
        await tester.pump();
        await tester.tap(find.text('19'));
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2017, DateTime.january, 19));
      });
    });

    testWidgets('Current year is visible in year picker', (WidgetTester tester) async {
530
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
531 532 533 534 535 536 537 538 539 540
        await tester.tap(find.text('January 2016')); // Switch to year mode.
        await tester.pump();
        expect(find.text('2016'), findsOneWidget);
      });
    });

    testWidgets('Cannot select a day outside bounds', (WidgetTester tester) async {
      initialDate = DateTime(2017, DateTime.january, 15);
      firstDate = initialDate;
      lastDate = initialDate;
541
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
542 543 544 545 546 547 548 549 550 551 552 553 554 555
        // Earlier than firstDate. Should be ignored.
        await tester.tap(find.text('10'));
        // Later than lastDate. Should be ignored.
        await tester.tap(find.text('20'));
        await tester.tap(find.text('OK'));
        // We should still be on the initial date.
        expect(await date, initialDate);
      });
    });

    testWidgets('Cannot select a month past last date', (WidgetTester tester) async {
      initialDate = DateTime(2017, DateTime.january, 15);
      firstDate = initialDate;
      lastDate = DateTime(2017, DateTime.february, 20);
556
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
557 558 559 560 561 562 563 564 565 566 567
        await tester.tap(nextMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        // Shouldn't be possible to keep going into March.
        expect(nextMonthIcon, findsNothing);
      });
    });

    testWidgets('Cannot select a month before first date', (WidgetTester tester) async {
      initialDate = DateTime(2017, DateTime.january, 15);
      firstDate = DateTime(2016, DateTime.december, 10);
      lastDate = initialDate;
568
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
569 570 571 572 573 574 575 576 577 578 579
        await tester.tap(previousMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        // Shouldn't be possible to keep going into November.
        expect(previousMonthIcon, findsNothing);
      });
    });

    testWidgets('Cannot select disabled year', (WidgetTester tester) async {
      initialDate = DateTime(2018, DateTime.july, 4);
      firstDate = DateTime(2018, DateTime.june, 9);
      lastDate = DateTime(2018, DateTime.december, 15);
580
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
581 582 583 584 585 586 587 588 589 590 591 592 593 594
        await tester.tap(find.text('July 2018')); // Switch to year mode.
        await tester.pumpAndSettle();
        await tester.tap(find.text('2016')); // Disabled, doesn't change the year.
        await tester.pumpAndSettle();
        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
        expect(await date, DateTime(2018, DateTime.july, 4));
      });
    });

    testWidgets('Selecting firstDate year respects firstDate', (WidgetTester tester) async {
      initialDate = DateTime(2018, DateTime.may, 4);
      firstDate = DateTime(2016, DateTime.june, 9);
      lastDate = DateTime(2019, DateTime.january, 15);
595
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
596 597 598 599 600 601 602 603 604 605 606 607 608
        await tester.tap(find.text('May 2018'));
        await tester.pumpAndSettle();
        await tester.tap(find.text('2016'));
        await tester.pumpAndSettle();
        // Month should be clamped to June as the range starts at June 2016
        expect(find.text('June 2016'), findsOneWidget);
      });
    });

    testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async {
      initialDate = DateTime(2018, DateTime.may, 4);
      firstDate = DateTime(2016, DateTime.june, 9);
      lastDate = DateTime(2019, DateTime.january, 15);
609
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
610 611 612 613 614 615 616
        await tester.tap(find.text('May 2018'));
        await tester.pumpAndSettle();
        await tester.tap(find.text('2019'));
        await tester.pumpAndSettle();
        // Month should be clamped to January as the range ends at January 2019
        expect(find.text('January 2019'), findsOneWidget);
      });
617 618
    });

619 620 621 622 623
    testWidgets('Only predicate days are selectable', (WidgetTester tester) async {
      initialDate = DateTime(2017, DateTime.january, 16);
      firstDate = DateTime(2017, DateTime.january, 10);
      lastDate = DateTime(2017, DateTime.january, 20);
      selectableDayPredicate = (DateTime day) => day.day.isEven;
624
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
625 626 627 628 629 630 631
        await tester.tap(find.text('13')); // Odd, doesn't work.
        await tester.tap(find.text('10')); // Even, works.
        await tester.tap(find.text('17')); // Odd, doesn't work.
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2017, DateTime.january, 10));
      });
    });
632

633
    testWidgets('Can select initial calendar picker mode', (WidgetTester tester) async {
634 635
      initialDate = DateTime(2014, DateTime.january, 15);
      initialCalendarMode = DatePickerMode.year;
636
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
637 638 639 640 641 642 643
        await tester.pump();
        // 2018 wouldn't be available if the year picker wasn't showing.
        // The initial current year is 2014.
        await tester.tap(find.text('2018'));
        await tester.pump();
        expect(find.text('January 2018'), findsOneWidget);
      });
644
    });
645

646 647
    testWidgets('currentDate is highlighted', (WidgetTester tester) async {
      today = DateTime(2016, 1, 2);
648
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
649 650 651 652 653
        await tester.pump();
        const Color todayColor = Color(0xff2196f3); // default primary color
        expect(
          Material.of(tester.element(find.text('2'))),
          // The current day should be painted with a circle outline
654
          paints..circle(color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0),
655 656 657
        );
      });
    });
658 659 660 661

    testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async {
      initialDate = DateTime(2020, DateTime.may, 10);
      initialCalendarMode = DatePickerMode.year;
662
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
663 664 665 666 667 668 669 670 671 672
        await tester.pump();
        await tester.tap(find.text('2017'));
        await tester.pump();
        expect(find.text('May 2017'), findsOneWidget);
        await tester.tap(find.text('10'));
        await tester.pump();
        expect(find.text('May 2017'), findsOneWidget);
        expect(find.text('2017'), findsNothing);
      });
    });
673
  });
674

675 676
  group('Input mode', () {
    setUp(() {
677
      firstDate = DateTime(2015);
678 679 680 681 682 683
      lastDate = DateTime(2017, DateTime.december, 31);
      initialDate = DateTime(2016, DateTime.january, 15);
      initialEntryMode = DatePickerEntryMode.input;
    });

    testWidgets('Initial entry mode is used', (WidgetTester tester) async {
684
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
685 686 687 688 689 690 691 692 693 694
        expect(find.byType(TextField), findsOneWidget);
      });
    });

    testWidgets('Hint, label, and help text is used', (WidgetTester tester) async {
      cancelText = 'nope';
      confirmText = 'yep';
      fieldHintText = 'hint';
      fieldLabelText = 'label';
      helpText = 'help';
695
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
696 697 698 699 700
        expect(find.text(cancelText!), findsOneWidget);
        expect(find.text(confirmText!), findsOneWidget);
        expect(find.text(fieldHintText!), findsOneWidget);
        expect(find.text(fieldLabelText!), findsOneWidget);
        expect(find.text(helpText!), findsOneWidget);
701 702 703 704
      });
    });

    testWidgets('Initial date is the default', (WidgetTester tester) async {
705
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
706 707 708 709 710 711
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.january, 15));
      });
    });

    testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async {
712
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
713 714 715 716 717 718 719 720
        expect(find.byType(TextField), findsOneWidget);
        await tester.tap(find.byIcon(Icons.calendar_today));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsNothing);
      });
    });

    testWidgets('Toggle to calendar mode keeps selected date', (WidgetTester tester) async {
721
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
722
        final TextField field = textField(tester);
723
        field.controller!.clear();
724 725 726 727 728 729 730 731 732 733

        await tester.enterText(find.byType(TextField), '12/25/2016');
        await tester.tap(find.byIcon(Icons.calendar_today));
        await tester.pumpAndSettle();
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.december, 25));
      });
    });

    testWidgets('Entered text returns date', (WidgetTester tester) async {
734
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
735
        final TextField field = textField(tester);
736
        field.controller!.clear();
737 738 739 740 741 742 743 744 745

        await tester.enterText(find.byType(TextField), '12/25/2016');
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.december, 25));
      });
    });

    testWidgets('Too short entered text shows error', (WidgetTester tester) async {
      errorFormatText = 'oops';
746
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
747
        final TextField field = textField(tester);
748
        field.controller!.clear();
749 750 751

        await tester.pumpAndSettle();
        await tester.enterText(find.byType(TextField), '1225');
752
        expect(find.text(errorFormatText!), findsNothing);
753 754 755

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
756
        expect(find.text(errorFormatText!), findsOneWidget);
757 758 759 760 761
      });
    });

    testWidgets('Bad format entered text shows error', (WidgetTester tester) async {
      errorFormatText = 'oops';
762
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
763
        final TextField field = textField(tester);
764
        field.controller!.clear();
765 766

        await tester.pumpAndSettle();
767 768
        await tester.enterText(find.byType(TextField), '20 days, 3 months, 2003');
        expect(find.text('20 days, 3 months, 2003'), findsOneWidget);
769
        expect(find.text(errorFormatText!), findsNothing);
770 771 772

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
773
        expect(find.text(errorFormatText!), findsOneWidget);
774 775 776 777 778
      });
    });

    testWidgets('Invalid entered text shows error', (WidgetTester tester) async {
      errorInvalidText = 'oops';
779
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
780
        final TextField field = textField(tester);
781
        field.controller!.clear();
782 783 784

        await tester.pumpAndSettle();
        await tester.enterText(find.byType(TextField), '08/10/1969');
785
        expect(find.text(errorInvalidText!), findsNothing);
786 787 788

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
789
        expect(find.text(errorInvalidText!), findsOneWidget);
790
      });
791
    });
792
  });
793

794
  group('Semantics', () {
795
    testWidgets('calendar mode', (WidgetTester tester) async {
796
      final SemanticsHandle semantics = tester.ensureSemantics();
797
      addTearDown(semantics.dispose);
798

799
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        // Header
        expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
          label: 'SELECT DATE\nFri, Jan 15',
        ));

        // Input mode toggle button
        expect(tester.getSemantics(switchToInputIcon), matchesSemantics(
          label: 'Switch to input',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));

815
        // The semantics of the CalendarDatePicker are tested in its tests.
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

        // Ok/Cancel buttons
        expect(tester.getSemantics(find.text('OK')), matchesSemantics(
          label: 'OK',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));
        expect(tester.getSemantics(find.text('CANCEL')), matchesSemantics(
          label: 'CANCEL',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));
      });
    });
836

837 838
    testWidgets('input mode', (WidgetTester tester) async {
      final SemanticsHandle semantics = tester.ensureSemantics();
839
      addTearDown(semantics.dispose);
840 841

      initialEntryMode = DatePickerEntryMode.input;
842
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        // Header
        expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
          label: 'SELECT DATE\nFri, Jan 15',
        ));

        // Input mode toggle button
        expect(tester.getSemantics(switchToCalendarIcon), matchesSemantics(
          label: 'Switch to calendar',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));

858
        // The semantics of the InputDatePickerFormField are tested in its tests.
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

        // Ok/Cancel buttons
        expect(tester.getSemantics(find.text('OK')), matchesSemantics(
          label: 'OK',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));
        expect(tester.getSemantics(find.text('CANCEL')), matchesSemantics(
          label: 'CANCEL',
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));
      });
    });
879
  });
880

881 882
  group('Keyboard navigation', () {
    testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async {
883
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
884 885 886 887 888 889
        expect(find.byType(TextField), findsNothing);
        // Navigate to the entry toggle button and activate it
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
890
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
891 892 893 894 895 896 897 898
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        // Should be in the input mode
        expect(find.byType(TextField), findsOneWidget);
      });
    });

    testWidgets('Can toggle to year mode', (WidgetTester tester) async {
899
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
900 901 902 903 904 905 906 907 908 909 910
        expect(find.text('2016'), findsNothing);
        // Navigate to the year selector and activate it
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        // The years should be visible
        expect(find.text('2016'), findsOneWidget);
      });
    });

    testWidgets('Can navigate next/previous months', (WidgetTester tester) async {
911
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
        expect(find.text('January 2016'), findsOneWidget);
        // Navigate to the previous month button and activate it twice
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        // Should be showing Nov 2015
        expect(find.text('November 2015'), findsOneWidget);

        // Navigate to the next month button and activate it four times
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        // Should be on Mar 2016
        expect(find.text('March 2016'), findsOneWidget);
      });
    });
937 938

    testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async {
939
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
        // Navigate to the grid
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);

        // Navigate from Jan 15 to Jan 18 with arrow keys
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.pumpAndSettle();

        // Activate it
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Navigate out of the grid and to the OK button
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);

        // Activate OK
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Should have selected Jan 18
        expect(await date, DateTime(2016, DateTime.january, 18));
      });
    });

    testWidgets('Navigating with arrow keys scrolls months', (WidgetTester tester) async {
975
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        // Navigate to the grid
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.pumpAndSettle();

        // Navigate from Jan 15 to Dec 31 with arrow keys
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.pumpAndSettle();

        // Should have scrolled to Dec 2015
        expect(find.text('December 2015'), findsOneWidget);

        // Navigate from Dec 31 to Nov 26 with arrow keys
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
        await tester.pumpAndSettle();

        // Should have scrolled to Nov 2015
        expect(find.text('November 2015'), findsOneWidget);

        // Activate it
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Navigate out of the grid and to the OK button
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.pumpAndSettle();

        // Activate OK
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Should have selected Jan 18
        expect(await date, DateTime(2015, DateTime.november, 26));
      });
    });

    testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async {
1023
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        // Navigate to the grid
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.pumpAndSettle();

        // Navigate from Jan 15 to 19 with arrow keys
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
        await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
        await tester.pumpAndSettle();

        // Activate it
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Navigate out of the grid and to the OK button
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.pumpAndSettle();

        // Activate OK
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();

        // Should have selected Jan 18
        expect(await date, DateTime(2016, DateTime.january, 19));
1056
      }, textDirection: TextDirection.rtl);
1057
    });
1058 1059
  });

1060
  group('Screen configurations', () {
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    // Test various combinations of screen sizes, orientations and text scales
    // to ensure the layout doesn't overflow and cause an exception to be thrown.

    // Regression tests for https://github.com/flutter/flutter/issues/21383
    // Regression tests for https://github.com/flutter/flutter/issues/19744
    // Regression tests for https://github.com/flutter/flutter/issues/17745

    // Common screen size roughly based on a Pixel 1
    const Size kCommonScreenSizePortrait = Size(1070, 1770);
    const Size kCommonScreenSizeLandscape = Size(1770, 1070);

    // Small screen size based on a LG K130
    const Size kSmallScreenSizePortrait = Size(320, 521);
    const Size kSmallScreenSizeLandscape = Size(521, 320);

    Future<void> _showPicker(WidgetTester tester, Size size, [double textScaleFactor = 1.0]) async {
      tester.binding.window.physicalSizeTestValue = size;
1078
      addTearDown(tester.binding.window.clearPhysicalSizeTestValue);
1079
      tester.binding.window.devicePixelRatioTestValue = 1.0;
1080
      addTearDown(tester.binding.window.clearDevicePixelRatioTestValue);
1081
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1082 1083
        await tester.tap(find.text('OK'));
      });
1084 1085 1086 1087 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 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
      await tester.pumpAndSettle();
    }

    testWidgets('common screen size - portrait', (WidgetTester tester) async {
      await _showPicker(tester, kCommonScreenSizePortrait);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - landscape', (WidgetTester tester) async {
      await _showPicker(tester, kCommonScreenSizeLandscape);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - portrait - textScale 1.3', (WidgetTester tester) async {
      await _showPicker(tester, kCommonScreenSizePortrait, 1.3);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - landscape - textScale 1.3', (WidgetTester tester) async {
      await _showPicker(tester, kCommonScreenSizeLandscape, 1.3);
      expect(tester.takeException(), isNull);
    });

    testWidgets('small screen size - portrait', (WidgetTester tester) async {
      await _showPicker(tester, kSmallScreenSizePortrait);
      expect(tester.takeException(), isNull);
    });

    testWidgets('small screen size - landscape', (WidgetTester tester) async {
      await _showPicker(tester, kSmallScreenSizeLandscape);
      expect(tester.takeException(), isNull);
    });

    testWidgets('small screen size - portrait -textScale 1.3', (WidgetTester tester) async {
      await _showPicker(tester, kSmallScreenSizePortrait, 1.3);
      expect(tester.takeException(), isNull);
    });

    testWidgets('small screen size - landscape - textScale 1.3', (WidgetTester tester) async {
      await _showPicker(tester, kSmallScreenSizeLandscape, 1.3);
      expect(tester.takeException(), isNull);
    });
  });
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

  testWidgets('DatePickerDialog is state restorable', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        restorationScopeId: 'app',
        home: _RestorableDatePickerDialogTestWidget(),
      ),
    );

    // The date picker should be closed.
    expect(find.byType(DatePickerDialog), findsNothing);
    expect(find.text('25/7/2021'), findsOneWidget);

    // Open the date picker.
    await tester.tap(find.text('X'));
    await tester.pumpAndSettle();
    expect(find.byType(DatePickerDialog), findsOneWidget);

    final TestRestorationData restorationData = await tester.getRestorationData();
    await tester.restartAndRestore();

    // The date picker should be open after restoring.
    expect(find.byType(DatePickerDialog), findsOneWidget);

    // Tap on the barrier.
    await tester.tapAt(const Offset(10.0, 10.0));
    await tester.pumpAndSettle();

    // The date picker should be closed, the text value updated to the
    // newly selected date.
    expect(find.byType(DatePickerDialog), findsNothing);
    expect(find.text('25/7/2021'), findsOneWidget);

    // The date picker should be open after restoring.
    await tester.restoreFrom(restorationData);
    expect(find.byType(DatePickerDialog), findsOneWidget);

1164
    // Select a different date.
1165 1166
    await tester.tap(find.text('30'));
    await tester.pumpAndSettle();
1167 1168 1169 1170 1171

    // Restart after the new selection. It should remain selected.
    await tester.restartAndRestore();

    // Close the date picker.
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    await tester.tap(find.text('OK'));
    await tester.pumpAndSettle();

    // The date picker should be closed, the text value updated to the
    // newly selected date.
    expect(find.byType(DatePickerDialog), findsNothing);
    expect(find.text('30/7/2021'), findsOneWidget);
  }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615

  testWidgets('DatePickerDialog state restoration - DatePickerEntryMode', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        restorationScopeId: 'app',
        home: _RestorableDatePickerDialogTestWidget(
          datePickerEntryMode: DatePickerEntryMode.calendarOnly,
        ),
      ),
    );

    // The date picker should be closed.
    expect(find.byType(DatePickerDialog), findsNothing);
    expect(find.text('25/7/2021'), findsOneWidget);

    // Open the date picker.
    await tester.tap(find.text('X'));
    await tester.pumpAndSettle();
    expect(find.byType(DatePickerDialog), findsOneWidget);

    // Only in calendar mode and cannot switch out.
    expect(find.byType(TextField), findsNothing);
    expect(find.byIcon(Icons.edit), findsNothing);

    final TestRestorationData restorationData = await tester.getRestorationData();
    await tester.restartAndRestore();

    // The date picker should be open after restoring.
    expect(find.byType(DatePickerDialog), findsOneWidget);
    // Only in calendar mode and cannot switch out.
    expect(find.byType(TextField), findsNothing);
    expect(find.byIcon(Icons.edit), findsNothing);

    // Tap on the barrier.
    await tester.tapAt(const Offset(10.0, 10.0));
    await tester.pumpAndSettle();

1217 1218
    // The date picker should be closed, the text value should be the same
    // as before.
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    expect(find.byType(DatePickerDialog), findsNothing);
    expect(find.text('25/7/2021'), findsOneWidget);

    // The date picker should be open after restoring.
    await tester.restoreFrom(restorationData);
    expect(find.byType(DatePickerDialog), findsOneWidget);
    // Only in calendar mode and cannot switch out.
    expect(find.byType(TextField), findsNothing);
    expect(find.byIcon(Icons.edit), findsNothing);
  }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615
}

class _RestorableDatePickerDialogTestWidget extends StatefulWidget {
  const _RestorableDatePickerDialogTestWidget({
    Key? key,
    this.datePickerEntryMode = DatePickerEntryMode.calendar,
  }) : super(key: key);

  final DatePickerEntryMode datePickerEntryMode;

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

class _RestorableDatePickerDialogTestWidgetState extends State<_RestorableDatePickerDialogTestWidget> with RestorationMixin {
  @override
  String? get restorationId => 'scaffold_state';

  final RestorableDateTime _selectedDate = RestorableDateTime(DateTime(2021, 7, 25));
  late final RestorableRouteFuture<DateTime?> _restorableDatePickerRouteFuture = RestorableRouteFuture<DateTime?>(
    onComplete: _selectDate,
    onPresent: (NavigatorState navigator, Object? arguments) {
      return navigator.restorablePush(
        _datePickerRoute,
        arguments: <String, dynamic>{
          'selectedDate': _selectedDate.value.millisecondsSinceEpoch,
          'datePickerEntryMode': widget.datePickerEntryMode.index,
1256
        },
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
      );
    },
  );

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(_selectedDate, 'selected_date');
    registerForRestoration(_restorableDatePickerRouteFuture, 'date_picker_route_future');
  }

  void _selectDate(DateTime? newSelectedDate) {
    if (newSelectedDate != null) {
      setState(() { _selectedDate.value = newSelectedDate; });
    }
  }

  static Route<DateTime> _datePickerRoute(
    BuildContext context,
    Object? arguments,
  ) {
    return DialogRoute<DateTime>(
      context: context,
      builder: (BuildContext context) {
        final Map<dynamic, dynamic> args = arguments! as Map<dynamic, dynamic>;
        return DatePickerDialog(
          restorationId: 'date_picker_dialog',
          initialEntryMode: DatePickerEntryMode.values[args['datePickerEntryMode'] as int],
          initialDate: DateTime.fromMillisecondsSinceEpoch(args['selectedDate'] as int),
1285 1286
          firstDate: DateTime(2021),
          lastDate: DateTime(2022),
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final DateTime selectedDateTime = _selectedDate.value;
    // Example: "25/7/1994"
    final String selectedDateTimeString = '${selectedDateTime.day}/${selectedDateTime.month}/${selectedDateTime.year}';
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            OutlinedButton(
              onPressed: () {
                _restorableDatePickerRouteFuture.present();
              },
              child: const Text('X'),
            ),
            Text(selectedDateTimeString),
          ],
        ),
      ),
    );
  }
1313 1314
}

1315
class _DatePickerObserver extends NavigatorObserver {
1316 1317 1318
  int datePickerCount = 0;

  @override
1319
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
1320
    if (route is DialogRoute) {
1321 1322 1323 1324
      datePickerCount++;
    }
    super.didPush(route, previousRoute);
  }
Ian Hickson's avatar
Ian Hickson committed
1325
}