date_picker_test.dart 90.1 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
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:ui';

7
import 'package:flutter/foundation.dart';
Ian Hickson's avatar
Ian Hickson committed
8
import 'package:flutter/material.dart';
9
import 'package:flutter/services.dart';
Ian Hickson's avatar
Ian Hickson committed
10
import 'package:flutter_test/flutter_test.dart';
11
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
Ian Hickson's avatar
Ian Hickson committed
12 13

void main() {
14
  TestWidgetsFlutterBinding.ensureInitialized();
15

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

  String? cancelText;
  String? confirmText;
  String? errorFormatText;
  String? errorInvalidText;
  String? fieldHintText;
  String? fieldLabelText;
  String? helpText;
32
  TextInputType? keyboardType;
33

34 35
  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));
36 37 38 39 40 41
  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));
  }
42

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

    cancelText = null;
    confirmText = null;
    errorFormatText = null;
    errorInvalidText = null;
    fieldHintText = null;
    fieldLabelText = null;
    helpText = null;
59
    keyboardType = null;
60
    currentMode = initialEntryMode;
61
  });
Ian Hickson's avatar
Ian Hickson committed
62

63 64 65
  const Size wideWindowSize = Size(1920.0, 1080.0);
  const Size narrowWindowSize = Size(1070.0, 1770.0);

66 67
  Future<void> prepareDatePicker(
    WidgetTester tester,
68 69
    Future<void> Function(Future<DateTime?> date) callback, {
    TextDirection textDirection = TextDirection.ltr,
70
    bool useMaterial3 = false,
71
    ThemeData? theme,
72
  }) async {
73
    late BuildContext buttonContext;
74
    await tester.pumpWidget(MaterialApp(
75
      theme: theme ?? ThemeData(useMaterial3: useMaterial3),
76 77
      home: Material(
        child: Builder(
78
          builder: (BuildContext context) {
79
            return ElevatedButton(
80 81 82
              onPressed: () {
                buttonContext = context;
              },
83
              child: const Text('Go'),
84 85 86 87 88 89 90 91 92
            );
          },
        ),
      ),
    ));

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

93
    final Future<DateTime?> date = showDatePicker(
94 95 96 97
      context: buttonContext,
      initialDate: initialDate,
      firstDate: firstDate,
      lastDate: lastDate,
98
      currentDate: today,
99 100 101 102 103 104 105 106 107 108
      selectableDayPredicate: selectableDayPredicate,
      initialDatePickerMode: initialCalendarMode,
      initialEntryMode: initialEntryMode,
      cancelText: cancelText,
      confirmText: confirmText,
      errorFormatText: errorFormatText,
      errorInvalidText: errorInvalidText,
      fieldHintText: fieldHintText,
      fieldLabelText: fieldLabelText,
      helpText: helpText,
109
      keyboardType: keyboardType,
110 111 112
      onDatePickerModeChange: (DatePickerEntryMode value) {
        currentMode = value;
      },
113
      builder: (BuildContext context, Widget? child) {
114 115
        return Directionality(
          textDirection: textDirection,
116
          child: child ?? const SizedBox(),
117 118
        );
      },
119
    );
120

121
    await tester.pumpAndSettle(const Duration(seconds: 1));
122 123 124
    await callback(date);
  }

125
  group('showDatePicker Dialog', () {
126
    testWidgetsWithLeakTracking('Default dialog size', (WidgetTester tester) async {
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
      Future<void> showPicker(WidgetTester tester, Size size) async {
        tester.view.physicalSize = size;
        tester.view.devicePixelRatio = 1.0;
        addTearDown(tester.view.reset);
        await prepareDatePicker(tester, (Future<DateTime?> date) async {}, useMaterial3: true);
      }
      const Size calendarLandscapeDialogSize = Size(496.0, 346.0);
      const Size calendarPortraitDialogSizeM3 = Size(328.0, 512.0);

      // Test landscape layout.
      await showPicker(tester, wideWindowSize);

      Size dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
      expect(dialogContainerSize, calendarLandscapeDialogSize);

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

      // Test portrait layout.
      await showPicker(tester, narrowWindowSize);

      dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
      expect(dialogContainerSize, calendarPortraitDialogSizeM3);
    });

153
    testWidgetsWithLeakTracking('Default dialog properties', (WidgetTester tester) async {
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      final ThemeData theme = ThemeData(useMaterial3: true);
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        final Material dialogMaterial = tester.widget<Material>(
          find.descendant(of: find.byType(Dialog),
          matching: find.byType(Material),
        ).first);

        expect(dialogMaterial.color, theme.colorScheme.surface);
        expect(dialogMaterial.shadowColor, Colors.transparent);
        expect(dialogMaterial.surfaceTintColor, theme.colorScheme.surfaceTint);
        expect(dialogMaterial.elevation, 6.0);
        expect(
          dialogMaterial.shape,
          const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))),
        );
        expect(dialogMaterial.clipBehavior, Clip.antiAlias);

        final Dialog dialog = tester.widget<Dialog>(find.byType(Dialog));
        expect(dialog.insetPadding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0));
      }, useMaterial3: theme.useMaterial3);
    });

176
    testWidgetsWithLeakTracking('Material3 uses sentence case labels', (WidgetTester tester) async {
177 178 179
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.text('Select date'), findsOneWidget);
      }, useMaterial3: true);
180
    });
181

182
    testWidgetsWithLeakTracking('Cancel, confirm, and help text is used', (WidgetTester tester) async {
183 184 185
      cancelText = 'nope';
      confirmText = 'yep';
      helpText = 'help';
186
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
187 188 189
        expect(find.text(cancelText!), findsOneWidget);
        expect(find.text(confirmText!), findsOneWidget);
        expect(find.text(helpText!), findsOneWidget);
190
      });
191 192
    });

193
    testWidgetsWithLeakTracking('Initial date is the default', (WidgetTester tester) async {
194
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
195 196 197
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.january, 15));
      });
198 199
    });

200
    testWidgetsWithLeakTracking('Can cancel', (WidgetTester tester) async {
201
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
202 203 204
        await tester.tap(find.text('CANCEL'));
        expect(await date, isNull);
      });
205 206
    });

207
    testWidgetsWithLeakTracking('Can switch from calendar to input entry mode', (WidgetTester tester) async {
208
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
209 210 211 212 213
        expect(find.byType(TextField), findsNothing);
        await tester.tap(find.byIcon(Icons.edit));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsOneWidget);
      });
214 215
    });

216
    testWidgetsWithLeakTracking('Can switch from input to calendar entry mode', (WidgetTester tester) async {
217 218 219 220 221 222 223 224 225
      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);
      });
    });

226
    testWidgetsWithLeakTracking('Can not switch out of calendarOnly mode', (WidgetTester tester) async {
227 228 229 230 231 232 233
      initialEntryMode = DatePickerEntryMode.calendarOnly;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.byType(TextField), findsNothing);
        expect(find.byIcon(Icons.edit), findsNothing);
      });
    });

234
    testWidgetsWithLeakTracking('Can not switch out of inputOnly mode', (WidgetTester tester) async {
235 236 237 238 239 240 241
      initialEntryMode = DatePickerEntryMode.inputOnly;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        expect(find.byType(TextField), findsOneWidget);
        expect(find.byIcon(Icons.calendar_today), findsNothing);
      });
    });

242
    testWidgetsWithLeakTracking('Switching to input mode keeps selected date', (WidgetTester tester) async {
243
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
244 245 246 247 248 249
        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));
      });
250 251
    });

252
    testWidgetsWithLeakTracking('Input only mode should validate date', (WidgetTester tester) async {
253 254 255 256 257 258 259 260 261 262
      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);
      });
    });

263
    testWidgetsWithLeakTracking('Switching to input mode resets input error state', (WidgetTester tester) async {
264
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
265 266 267 268 269 270 271 272
        // 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);

273
        // Toggle to calendar mode and then back to input mode
274 275 276 277 278 279 280 281 282 283 284 285 286
        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);
      });
    });

287
    testWidgetsWithLeakTracking('builder parameter', (WidgetTester tester) async {
288 289 290 291 292 293
      Widget buildFrame(TextDirection textDirection) {
        return MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
294
                  return ElevatedButton(
295 296 297 298 299 300 301
                    child: const Text('X'),
                    onPressed: () {
                      showDatePicker(
                        context: context,
                        initialDate: DateTime.now(),
                        firstDate: DateTime(2018),
                        lastDate: DateTime(2030),
302
                        builder: (BuildContext context, Widget? child) {
303 304
                          return Directionality(
                            textDirection: textDirection,
305
                            child: child ?? const SizedBox(),
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                          );
                        },
                      );
                    },
                  );
                },
              ),
            ),
          ),
        );
      }

      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'
333
      // button and the right edge of the 800 wide view.
334
      expect(tester.getBottomLeft(find.text('OK')).dx, moreOrLessEquals(800 - ltrOkRight));
335 336
    });

337 338 339 340 341 342 343
    group('Barrier dismissible', () {
      late _DatePickerObserver rootObserver;

      setUp(() {
        rootObserver = _DatePickerObserver();
      });

344
      testWidgetsWithLeakTracking('Barrier is dismissible with default parameter', (WidgetTester tester) async {
345 346 347 348 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
        await tester.pumpWidget(
          MaterialApp(
            navigatorObservers: <NavigatorObserver>[rootObserver],
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () =>
                          showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(2018),
                            lastDate: DateTime(2030),
                            builder: (BuildContext context,
                                Widget? child) => const SizedBox(),
                          ),
                    );
                  },
                ),
              ),
            ),
          ),
        );

        // Open the dialog.
        await tester.tap(find.byType(ElevatedButton));
        await tester.pumpAndSettle();
        expect(rootObserver.datePickerCount, 1);

        // Tap on the barrier.
        await tester.tapAt(const Offset(10.0, 10.0));
        await tester.pumpAndSettle();
        expect(rootObserver.datePickerCount, 0);
      });

382
      testWidgetsWithLeakTracking('Barrier is not dismissible with barrierDismissible is false', (WidgetTester tester) async {
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        await tester.pumpWidget(
          MaterialApp(
            navigatorObservers: <NavigatorObserver>[rootObserver],
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () =>
                          showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(2018),
                            lastDate: DateTime(2030),
                            barrierDismissible: false,
                            builder: (BuildContext context,
                                Widget? child) => const SizedBox(),
                          ),
                    );
                  },
                ),
              ),
            ),
          ),
        );

        // Open the dialog.
        await tester.tap(find.byType(ElevatedButton));
        await tester.pumpAndSettle();
        expect(rootObserver.datePickerCount, 1);

        // Tap on the barrier, which shouldn't do anything this time.
        await tester.tapAt(const Offset(10.0, 10.0));
        await tester.pumpAndSettle();
        expect(rootObserver.datePickerCount, 1);
      });
    });

422
    testWidgetsWithLeakTracking('Barrier color', (WidgetTester tester) async {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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
      await tester.pumpWidget(
        MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    child: const Text('X'),
                    onPressed: () =>
                        showDatePicker(
                          context: context,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(2018),
                          lastDate: DateTime(2030),
                          builder: (BuildContext context,
                              Widget? child) => const SizedBox(),
                        ),
                  );
                },
              ),
            ),
          ),
        ),
      );

      // Open the dialog.
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.black54);

      // Dismiss the dialog.
      await tester.tapAt(const Offset(10.0, 10.0));

      await tester.pumpWidget(
        MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    child: const Text('X'),
                    onPressed: () =>
                        showDatePicker(
                          context: context,
                          barrierColor: Colors.pink,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(2018),
                          lastDate: DateTime(2030),
                          builder: (BuildContext context,
                              Widget? child) => const SizedBox(),
                        ),
                  );
                },
              ),
            ),
          ),
        ),
      );

      // Open the dialog.
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.pink);
    });

488
    testWidgetsWithLeakTracking('Barrier Label', (WidgetTester tester) async {
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
      await tester.pumpWidget(
        MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    child: const Text('X'),
                    onPressed: () =>
                        showDatePicker(
                          context: context,
                          barrierLabel: 'Custom Label',
                          initialDate: DateTime.now(),
                          firstDate: DateTime(2018),
                          lastDate: DateTime(2030),
                          builder: (BuildContext context,
                              Widget? child) => const SizedBox(),
                        ),
                  );
                },
              ),
            ),
          ),
        ),
      );

      // Open the dialog.
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).semanticsLabel, 'Custom Label');
    });

521
    testWidgetsWithLeakTracking('uses nested navigator if useRootNavigator is false', (WidgetTester tester) async {
522 523 524 525 526 527 528 529 530 531
      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) {
532
                return ElevatedButton(
533 534 535 536 537 538 539
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      useRootNavigator: false,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
540
                      builder: (BuildContext context, Widget? child) => const SizedBox(),
541 542 543 544 545 546 547 548 549 550 551
                    );
                  },
                  child: const Text('Show Date Picker'),
                );
              },
            );
          },
        ),
      ));

      // Open the dialog.
552
      await tester.tap(find.byType(ElevatedButton));
553 554 555

      expect(rootObserver.datePickerCount, 0);
      expect(nestedObserver.datePickerCount, 1);
556
    });
557

558
    testWidgetsWithLeakTracking('honors DialogTheme for shape and elevation', (WidgetTester tester) async {
559 560 561
      // Test that the defaults work
      const DialogTheme datePickerDefaultDialogTheme = DialogTheme(
        shape: RoundedRectangleBorder(
562
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
563 564 565 566 567
        ),
        elevation: 24,
      );
      await tester.pumpWidget(
        MaterialApp(
568
          theme: ThemeData(useMaterial3: false),
569 570 571
          home: Center(
            child: Builder(
              builder: (BuildContext context) {
572
                return ElevatedButton(
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
                  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();
590 591
      final Material defaultDialogMaterial = tester.widget<Material>(find.descendant(
        of: find.byType(Dialog), matching: find.byType(Material)).first);
592 593 594 595 596 597
      expect(defaultDialogMaterial.shape, datePickerDefaultDialogTheme.shape);
      expect(defaultDialogMaterial.elevation, datePickerDefaultDialogTheme.elevation);

      // Test that it honors ThemeData.dialogTheme settings
      const DialogTheme customDialogTheme = DialogTheme(
        shape: RoundedRectangleBorder(
598
          borderRadius: BorderRadius.all(Radius.circular(40.0)),
599 600 601 602 603
        ),
        elevation: 50,
      );
      await tester.pumpWidget(
        MaterialApp(
604
          theme: ThemeData.fallback(useMaterial3: false).copyWith(dialogTheme: customDialogTheme),
605 606 607
          home: Center(
            child: Builder(
              builder: (BuildContext context) {
608
                return ElevatedButton(
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                  child: const Text('X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
                    );
                  },
                );
              },
            ),
          ),
        ),
      );
624 625
      await tester.pump(); // start theme animation
      await tester.pump(const Duration(seconds: 5)); // end theme animation
626 627 628 629 630
      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);
    });

631
    testWidgetsWithLeakTracking('OK Cancel button layout', (WidgetTester tester) async {
632 633
       Widget buildFrame(TextDirection textDirection) {
         return MaterialApp(
634
           theme: ThemeData(useMaterial3: false),
635 636 637 638 639 640 641 642 643 644
           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),
645
                         firstDate:DateTime(2001),
646
                         lastDate: DateTime(2031, DateTime.december, 31),
647
                         builder: (BuildContext context, Widget? child) {
648 649
                           return Directionality(
                             textDirection: textDirection,
650
                             child: child ?? const SizedBox(),
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
                           );
                         },
                       );
                     },
                   );
                 },
               ),
             ),
           ),
         );
       }

      // 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.

685 686
      addTearDown(tester.view.reset);
      tester.view.physicalSize = const Size(900, 1200);
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

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

707
    testWidgetsWithLeakTracking('honors switchToInputEntryModeIcon', (WidgetTester tester) async {
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
      Widget buildApp({bool? useMaterial3, Icon? switchToInputEntryModeIcon}) {
       return MaterialApp(
          theme: ThemeData(
            useMaterial3: useMaterial3 ?? false,
          ),
          home: Material(
            child: Builder(
              builder: (BuildContext context) {
                return ElevatedButton(
                  child: const Text('Click X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
                      switchToInputEntryModeIcon: switchToInputEntryModeIcon,
                    );
                  },
                );
              },
            ),
          ),
        );
      }

      await tester.pumpWidget(buildApp());
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.edit), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(buildApp(useMaterial3: true));
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.edit_outlined), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(
        buildApp(
          switchToInputEntryModeIcon: const Icon(Icons.keyboard),
        ),
      );
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.keyboard), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();
    });

763
    testWidgetsWithLeakTracking('honors switchToCalendarEntryModeIcon', (WidgetTester tester) async {
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
      Widget buildApp({bool? useMaterial3, Icon? switchToCalendarEntryModeIcon}) {
       return MaterialApp(
          theme: ThemeData(
            useMaterial3: useMaterial3 ?? false,
          ),
          home: Material(
            child: Builder(
              builder: (BuildContext context) {
                return ElevatedButton(
                  child: const Text('Click X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2018),
                      lastDate: DateTime(2030),
                      switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon,
                      initialEntryMode: DatePickerEntryMode.input,
                    );
                  },
                );
              },
            ),
          ),
        );
      }

      await tester.pumpWidget(buildApp());
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.calendar_today), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(buildApp(useMaterial3: true));
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.calendar_today), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();

      await tester.pumpWidget(
        buildApp(
          switchToCalendarEntryModeIcon: const Icon(Icons.favorite),
        ),
      );
      await tester.pumpAndSettle();
      await tester.tap(find.byType(ElevatedButton));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.favorite), findsOneWidget);
      await tester.tap(find.text('OK'));
      await tester.pumpAndSettle();
    });
819
  });
820

821
  group('Calendar mode', () {
822
    testWidgetsWithLeakTracking('Default Calendar mode layout (Landscape)', (WidgetTester tester) async {
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 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 877 878 879
      final Finder helpText = find.text('Select date');
      final Finder headerText = find.text('Fri, Jan 15');
      final Finder subHeaderText = find.text('January 2016');
      final Finder cancelButtonText = find.text('Cancel');
      final Finder okButtonText = find.text('OK');
      const EdgeInsets insetPadding = EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0);

      tester.view.physicalSize = wideWindowSize;
      addTearDown(tester.view.reset);

      await tester.pumpWidget(MaterialApp(
        theme: ThemeData(useMaterial3: true),
        home: Material(
          child: DatePickerDialog(
            initialDate: initialDate,
            firstDate: firstDate,
            lastDate: lastDate,
          ),
        ),
      ));

      expect(helpText, findsOneWidget);
      expect(headerText, findsOneWidget);
      expect(subHeaderText, findsOneWidget);
      expect(cancelButtonText, findsOneWidget);
      expect(okButtonText, findsOneWidget);

      // Test help text position.
      final Offset dialogTopLeft = tester.getTopLeft(find.byType(AnimatedContainer));
      final Offset helpTextTopLeft = tester.getTopLeft(helpText);
      expect(helpTextTopLeft.dx, dialogTopLeft.dx + (insetPadding.horizontal / 2));
      expect(helpTextTopLeft.dy, dialogTopLeft.dy + 16.0);

      // Test header text position.
      final Offset headerTextTopLeft = tester.getTopLeft(headerText);
      final Offset helpTextBottomLeft = tester.getBottomLeft(helpText);
      expect(headerTextTopLeft.dx, dialogTopLeft.dx + (insetPadding.horizontal / 2));
      expect(headerTextTopLeft.dy, helpTextBottomLeft.dy + 16.0);

      // Test switch button position.
      final Finder switchButtonM3 = find.widgetWithIcon(IconButton, Icons.edit_outlined);
      final Offset switchButtonTopLeft = tester.getTopLeft(switchButtonM3);
      final Offset headerTextBottomLeft = tester.getBottomLeft(headerText);
      expect(switchButtonTopLeft.dx, dialogTopLeft.dx + 4.0);
      expect(switchButtonTopLeft.dy, headerTextBottomLeft.dy);

      // Test vertical divider position.
      final Finder divider = find.byType(VerticalDivider);
      final Offset dividerTopLeft = tester.getTopLeft(divider);
      final Offset headerTextTopRiught = tester.getTopRight(headerText);
      expect(dividerTopLeft.dx, headerTextTopRiught.dx + 16.0);
      expect(dividerTopLeft.dy, dialogTopLeft.dy);

      // Test sub header text position.
      final Offset subHeaderTextTopLeft = tester.getTopLeft(subHeaderText);
      final Offset dividerTopRight = tester.getTopRight(divider);
      expect(subHeaderTextTopLeft.dx, dividerTopRight.dx + 24.0);
880 881 882
      if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
        expect(subHeaderTextTopLeft.dy,  dialogTopLeft.dy + 16.0);
      }
883 884 885 886 887 888 889 890 891 892 893 894 895

      // Test sub header icon position.
      final Finder subHeaderIcon = find.byIcon(Icons.arrow_drop_down);
      final Offset subHeaderIconTopLeft = tester.getTopLeft(subHeaderIcon);
      final Offset subHeaderTextTopRight = tester.getTopRight(subHeaderText);
      expect(subHeaderIconTopLeft.dx, subHeaderTextTopRight.dx);
      expect(subHeaderIconTopLeft.dy, dialogTopLeft.dy + 14.0);

      // Test calendar page view position.
      final Finder calendarPageView = find.byType(PageView);
      final Offset calendarPageViewTopLeft = tester.getTopLeft(calendarPageView);
      final Offset subHeaderTextBottomLeft = tester.getBottomLeft(subHeaderText);
      expect(calendarPageViewTopLeft.dx, dividerTopRight.dx);
896 897 898
      if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
        expect(calendarPageViewTopLeft.dy, subHeaderTextBottomLeft.dy + 16.0);
      }
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

      // Test month navigation icons position.
      final Finder previousMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_left);
      final Finder nextMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_right);
      final Offset previousMonthButtonTopRight = tester.getTopRight(previousMonthButton);
      final Offset nextMonthButtonTopRight = tester.getTopRight(nextMonthButton);
      final Offset dialogTopRight = tester.getTopRight(find.byType(AnimatedContainer));
      expect(nextMonthButtonTopRight.dx, dialogTopRight.dx - 4.0);
      expect(nextMonthButtonTopRight.dy, dialogTopRight.dy + 2.0);
      expect(previousMonthButtonTopRight.dx, nextMonthButtonTopRight.dx - 48.0);

      // Test action buttons position.
      final Offset dialogBottomRight = tester.getBottomRight(find.byType(AnimatedContainer));
      final Offset okButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'OK'));
      final Offset cancelButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'Cancel'));
      final Offset calendarPageViewBottomRight = tester.getBottomRight(calendarPageView);
      expect(okButtonTopRight.dx, dialogBottomRight.dx - 8);
      expect(okButtonTopRight.dy, calendarPageViewBottomRight.dy + 2);
      final Offset okButtonTopLeft = tester.getTopLeft(find.widgetWithText(TextButton, 'OK'));
      expect(cancelButtonTopRight.dx, okButtonTopLeft.dx - 8);
    });

921
    testWidgetsWithLeakTracking('Default Calendar mode layout (Portrait)', (WidgetTester tester) async {
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 955 956 957
      final Finder helpText = find.text('Select date');
      final Finder headerText = find.text('Fri, Jan 15');
      final Finder subHeaderText = find.text('January 2016');
      final Finder cancelButtonText = find.text('Cancel');
      final Finder okButtonText = find.text('OK');

      tester.view.physicalSize = narrowWindowSize;
      addTearDown(tester.view.reset);

      await tester.pumpWidget(MaterialApp(
        theme: ThemeData(useMaterial3: true),
        home: Material(
          child: DatePickerDialog(
            initialDate: initialDate,
            firstDate: firstDate,
            lastDate: lastDate,
          ),
        ),
      ));

      expect(helpText, findsOneWidget);
      expect(headerText, findsOneWidget);
      expect(subHeaderText, findsOneWidget);
      expect(cancelButtonText, findsOneWidget);
      expect(okButtonText, findsOneWidget);

      // Test help text position.
      final Offset dialogTopLeft = tester.getTopLeft(find.byType(AnimatedContainer));
      final Offset helpTextTopLeft = tester.getTopLeft(helpText);
      expect(helpTextTopLeft.dx, dialogTopLeft.dx + 24.0);
      expect(helpTextTopLeft.dy, dialogTopLeft.dy + 16.0);

      // Test header text position
      final Offset headerTextTextTopLeft = tester.getTopLeft(headerText);
      final Offset helpTextBottomLeft = tester.getBottomLeft(helpText);
      expect(headerTextTextTopLeft.dx, dialogTopLeft.dx + 24.0);
958 959 960
      if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
        expect(headerTextTextTopLeft.dy, helpTextBottomLeft.dy + 28.0);
      }
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979

      // Test switch button position.
      final Finder switchButtonM3 = find.widgetWithIcon(IconButton, Icons.edit_outlined);
      final Offset switchButtonTopRight = tester.getTopRight(switchButtonM3);
      final Offset dialogTopRight = tester.getTopRight(find.byType(AnimatedContainer));
      expect(switchButtonTopRight.dx, dialogTopRight.dx - 12.0);
      expect(switchButtonTopRight.dy, headerTextTextTopLeft.dy - 4.0);

      // Test horizontal divider position.
      final Finder divider = find.byType(Divider);
      final Offset dividerTopLeft = tester.getTopLeft(divider);
      final Offset headerTextBottomLeft = tester.getBottomLeft(headerText);
      expect(dividerTopLeft.dx, dialogTopLeft.dx);
      expect(dividerTopLeft.dy, headerTextBottomLeft.dy + 16.0);

      // Test subHeaderText position.
      final Offset subHeaderTextTopLeft = tester.getTopLeft(subHeaderText);
      final Offset dividerBottomLeft = tester.getBottomLeft(divider);
      expect(subHeaderTextTopLeft.dx, dialogTopLeft.dx + 24.0);
980 981 982
      if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
        expect(subHeaderTextTopLeft.dy, dividerBottomLeft.dy + 16.0);
      }
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

      // Test sub header icon position.
      final Finder subHeaderIcon = find.byIcon(Icons.arrow_drop_down);
      final Offset subHeaderIconTopLeft = tester.getTopLeft(subHeaderIcon);
      final Offset subHeaderTextTopRight = tester.getTopRight(subHeaderText);
      expect(subHeaderIconTopLeft.dx, subHeaderTextTopRight.dx);
      expect(subHeaderIconTopLeft.dy, dividerBottomLeft.dy + 14.0);

      // Test month navigation icons position.
      final Finder previousMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_left);
      final Finder nextMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_right);
      final Offset previousMonthButtonTopRight = tester.getTopRight(previousMonthButton);
      final Offset nextMonthButtonTopRight = tester.getTopRight(nextMonthButton);
      expect(nextMonthButtonTopRight.dx, dialogTopRight.dx - 4.0);
      expect(nextMonthButtonTopRight.dy, dividerBottomLeft.dy + 2.0);
      expect(previousMonthButtonTopRight.dx, nextMonthButtonTopRight.dx - 48.0);

      // Test calendar page view position.
      final Finder calendarPageView = find.byType(PageView);
      final Offset calendarPageViewTopLeft = tester.getTopLeft(calendarPageView);
      final Offset subHeaderTextBottomLeft = tester.getBottomLeft(subHeaderText);
      expect(calendarPageViewTopLeft.dx, dialogTopLeft.dx);
1005 1006 1007
      if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
        expect(calendarPageViewTopLeft.dy, subHeaderTextBottomLeft.dy + 16.0);
      }
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

      // Test action buttons position.
      final Offset dialogBottomRight = tester.getBottomRight(find.byType(AnimatedContainer));
      final Offset okButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'OK'));
      final Offset cancelButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'Cancel'));
      final Offset calendarPageViewBottomRight = tester.getBottomRight(calendarPageView);
      final Offset okButtonTopLeft = tester.getTopLeft(find.widgetWithText(TextButton, 'OK'));
      expect(okButtonTopRight.dx, dialogBottomRight.dx - 8);
      expect(okButtonTopRight.dy, calendarPageViewBottomRight.dy + 2);
      expect(cancelButtonTopRight.dx, okButtonTopLeft.dx - 8);
    });

1020
    testWidgetsWithLeakTracking('Can select a day', (WidgetTester tester) async {
1021
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1022 1023 1024 1025
        await tester.tap(find.text('12'));
        await tester.tap(find.text('OK'));
        expect(await date, equals(DateTime(2016, DateTime.january, 12)));
      });
1026 1027
    });

1028
    testWidgetsWithLeakTracking('Can select a month', (WidgetTester tester) async {
1029
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1030 1031 1032 1033 1034 1035
        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));
      });
1036 1037
    });

1038
    testWidgetsWithLeakTracking('Can select a year', (WidgetTester tester) async {
1039
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1040 1041 1042 1043 1044 1045
        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);
      });
1046
    });
1047

1048
    testWidgetsWithLeakTracking('Can select a day with no initial date', (WidgetTester tester) async {
1049 1050 1051 1052 1053 1054 1055 1056
      initialDate = null;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        await tester.tap(find.text('12'));
        await tester.tap(find.text('OK'));
        expect(await date, equals(DateTime(2016, DateTime.january, 12)));
      });
    });

1057
    testWidgetsWithLeakTracking('Can select a month with no initial date', (WidgetTester tester) async {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
      initialDate = null;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        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));
      });
    });

1068
    testWidgetsWithLeakTracking('Can select a year with no initial date', (WidgetTester tester) async {
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
      initialDate = null;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        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);
      });
    });

1079
    testWidgetsWithLeakTracking('Selecting date does not change displayed month', (WidgetTester tester) async {
1080
      initialDate = DateTime(2020, DateTime.march, 15);
1081
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        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);
      });
    });

1093
    testWidgetsWithLeakTracking('Changing year does change selected date', (WidgetTester tester) async {
1094
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1095 1096 1097 1098 1099
        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'));
1100
        expect(await date, equals(DateTime(2018, DateTime.january, 15)));
1101
      });
1102 1103
    });

1104
    testWidgetsWithLeakTracking('Changing year does not change the month', (WidgetTester tester) async {
1105
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
        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);
      });
    });

1118
    testWidgetsWithLeakTracking('Can select a year and then a day', (WidgetTester tester) async {
1119
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        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));
      });
    });

1130
    testWidgetsWithLeakTracking('Current year is visible in year picker', (WidgetTester tester) async {
1131
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1132 1133 1134 1135 1136 1137
        await tester.tap(find.text('January 2016')); // Switch to year mode.
        await tester.pump();
        expect(find.text('2016'), findsOneWidget);
      });
    });

1138
    testWidgetsWithLeakTracking('Cannot select a day outside bounds', (WidgetTester tester) async {
1139
      initialDate = DateTime(2017, DateTime.january, 15);
1140 1141
      firstDate = initialDate!;
      lastDate = initialDate!;
1142
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        // 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);
      });
    });

1153
    testWidgetsWithLeakTracking('Cannot select a month past last date', (WidgetTester tester) async {
1154
      initialDate = DateTime(2017, DateTime.january, 15);
1155
      firstDate = initialDate!;
1156
      lastDate = DateTime(2017, DateTime.february, 20);
1157
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1158 1159 1160 1161 1162 1163 1164
        await tester.tap(nextMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        // Shouldn't be possible to keep going into March.
        expect(nextMonthIcon, findsNothing);
      });
    });

1165
    testWidgetsWithLeakTracking('Cannot select a month before first date', (WidgetTester tester) async {
1166 1167
      initialDate = DateTime(2017, DateTime.january, 15);
      firstDate = DateTime(2016, DateTime.december, 10);
1168
      lastDate = initialDate!;
1169
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1170 1171 1172 1173 1174 1175 1176
        await tester.tap(previousMonthIcon);
        await tester.pumpAndSettle(const Duration(seconds: 1));
        // Shouldn't be possible to keep going into November.
        expect(previousMonthIcon, findsNothing);
      });
    });

1177
    testWidgetsWithLeakTracking('Cannot select disabled year', (WidgetTester tester) async {
1178 1179 1180
      initialDate = DateTime(2018, DateTime.july, 4);
      firstDate = DateTime(2018, DateTime.june, 9);
      lastDate = DateTime(2018, DateTime.december, 15);
1181
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        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));
      });
    });

1192
    testWidgetsWithLeakTracking('Selecting firstDate year respects firstDate', (WidgetTester tester) async {
1193 1194 1195
      initialDate = DateTime(2018, DateTime.may, 4);
      firstDate = DateTime(2016, DateTime.june, 9);
      lastDate = DateTime(2019, DateTime.january, 15);
1196
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1197 1198 1199 1200 1201 1202 1203 1204 1205
        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);
      });
    });

1206
    testWidgetsWithLeakTracking('Selecting lastDate year respects lastDate', (WidgetTester tester) async {
1207 1208 1209
      initialDate = DateTime(2018, DateTime.may, 4);
      firstDate = DateTime(2016, DateTime.june, 9);
      lastDate = DateTime(2019, DateTime.january, 15);
1210
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1211 1212 1213 1214 1215 1216 1217
        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);
      });
1218 1219
    });

1220
    testWidgetsWithLeakTracking('Only predicate days are selectable', (WidgetTester tester) async {
1221 1222 1223 1224
      initialDate = DateTime(2017, DateTime.january, 16);
      firstDate = DateTime(2017, DateTime.january, 10);
      lastDate = DateTime(2017, DateTime.january, 20);
      selectableDayPredicate = (DateTime day) => day.day.isEven;
1225
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1226 1227 1228 1229 1230 1231 1232
        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));
      });
    });
1233

1234
    testWidgetsWithLeakTracking('Can select initial calendar picker mode', (WidgetTester tester) async {
1235 1236
      initialDate = DateTime(2014, DateTime.january, 15);
      initialCalendarMode = DatePickerMode.year;
1237
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1238 1239 1240 1241 1242 1243 1244
        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);
      });
1245
    });
1246

1247
    testWidgetsWithLeakTracking('currentDate is highlighted', (WidgetTester tester) async {
1248
      today = DateTime(2016, 1, 2);
1249
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1250 1251 1252 1253 1254
        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
1255
          paints..circle(color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0),
1256 1257 1258
        );
      });
    });
1259

1260
    testWidgetsWithLeakTracking('Date picker dayOverlayColor resolves pressed state', (WidgetTester tester) async {
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
      today = DateTime(2023, 5, 4);
      final ThemeData theme = ThemeData();
      final bool material3 = theme.useMaterial3;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        await tester.pump();

        // Hovered.
        final Offset center = tester.getCenter(find.text('30'));
        final TestGesture gesture = await tester.createGesture(
          kind: PointerDeviceKind.mouse,
        );
        await gesture.addPointer();
        await gesture.moveTo(center);
        await tester.pumpAndSettle();
        expect(
          Material.of(tester.element(find.text('30'))),
          paints..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.08) : theme.colorScheme.onSurfaceVariant.withOpacity(0.08)),
        );

        // Highlighted (pressed).
        await gesture.down(center);
        await tester.pumpAndSettle();
        expect(
          Material.of(tester.element(find.text('30'))),
          paints..circle()..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.12) : theme.colorScheme.onSurfaceVariant.withOpacity(0.12))
        );
        await gesture.up();
        await tester.pumpAndSettle();
      }, theme: theme);
    });

1292
    testWidgetsWithLeakTracking('Selecting date does not switch picker to year selection', (WidgetTester tester) async {
1293 1294
      initialDate = DateTime(2020, DateTime.may, 10);
      initialCalendarMode = DatePickerMode.year;
1295
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        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);
      });
    });
1306
  });
1307

1308 1309
  group('Input mode', () {
    setUp(() {
1310
      firstDate = DateTime(2015);
1311 1312 1313 1314 1315
      lastDate = DateTime(2017, DateTime.december, 31);
      initialDate = DateTime(2016, DateTime.january, 15);
      initialEntryMode = DatePickerEntryMode.input;
    });

1316
    testWidgetsWithLeakTracking('Default InputDecoration', (WidgetTester tester) async {
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        final InputDecoration decoration = tester.widget<TextField>(
          find.byType(TextField)).decoration!;
        expect(decoration.border, const OutlineInputBorder());
        expect(decoration.filled, false);
        expect(decoration.hintText, 'mm/dd/yyyy');
        expect(decoration.labelText, 'Enter Date');
        expect(decoration.errorText, null);
      }, useMaterial3: true);
    });

1328
    testWidgetsWithLeakTracking('Initial entry mode is used', (WidgetTester tester) async {
1329
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1330 1331 1332 1333
        expect(find.byType(TextField), findsOneWidget);
      });
    });

1334
    testWidgetsWithLeakTracking('Hint, label, and help text is used', (WidgetTester tester) async {
1335 1336 1337 1338 1339
      cancelText = 'nope';
      confirmText = 'yep';
      fieldHintText = 'hint';
      fieldLabelText = 'label';
      helpText = 'help';
1340
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1341 1342 1343 1344 1345
        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);
1346 1347 1348
      });
    });

1349
    testWidgetsWithLeakTracking('KeyboardType is used', (WidgetTester tester) async {
1350 1351 1352 1353 1354 1355 1356
      keyboardType = TextInputType.text;
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        final TextField field = textField(tester);
        expect(field.keyboardType, TextInputType.text);
      });
    });

1357
    testWidgetsWithLeakTracking('Initial date is the default', (WidgetTester tester) async {
1358
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1359 1360 1361 1362 1363
        await tester.tap(find.text('OK'));
        expect(await date, DateTime(2016, DateTime.january, 15));
      });
    });

1364
    testWidgetsWithLeakTracking('Can toggle to calendar entry mode', (WidgetTester tester) async {
1365
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1366 1367 1368 1369 1370 1371 1372
        expect(find.byType(TextField), findsOneWidget);
        await tester.tap(find.byIcon(Icons.calendar_today));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsNothing);
      });
    });

1373
    testWidgetsWithLeakTracking('Toggle to calendar mode keeps selected date', (WidgetTester tester) async {
1374
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1375
        final TextField field = textField(tester);
1376
        field.controller!.clear();
1377 1378 1379 1380 1381 1382 1383 1384 1385

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

1386
    testWidgetsWithLeakTracking('Entered text returns date', (WidgetTester tester) async {
1387
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1388
        final TextField field = textField(tester);
1389
        field.controller!.clear();
1390 1391 1392 1393 1394 1395 1396

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

1397
    testWidgetsWithLeakTracking('Too short entered text shows error', (WidgetTester tester) async {
1398
      errorFormatText = 'oops';
1399
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1400
        final TextField field = textField(tester);
1401
        field.controller!.clear();
1402 1403 1404

        await tester.pumpAndSettle();
        await tester.enterText(find.byType(TextField), '1225');
1405
        expect(find.text(errorFormatText!), findsNothing);
1406 1407 1408

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
1409
        expect(find.text(errorFormatText!), findsOneWidget);
1410 1411 1412
      });
    });

1413
    testWidgetsWithLeakTracking('Bad format entered text shows error', (WidgetTester tester) async {
1414
      errorFormatText = 'oops';
1415
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1416
        final TextField field = textField(tester);
1417
        field.controller!.clear();
1418 1419

        await tester.pumpAndSettle();
1420 1421
        await tester.enterText(find.byType(TextField), '20 days, 3 months, 2003');
        expect(find.text('20 days, 3 months, 2003'), findsOneWidget);
1422
        expect(find.text(errorFormatText!), findsNothing);
1423 1424 1425

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
1426
        expect(find.text(errorFormatText!), findsOneWidget);
1427 1428 1429
      });
    });

1430
    testWidgetsWithLeakTracking('Invalid entered text shows error', (WidgetTester tester) async {
1431
      errorInvalidText = 'oops';
1432
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1433
        final TextField field = textField(tester);
1434
        field.controller!.clear();
1435 1436 1437

        await tester.pumpAndSettle();
        await tester.enterText(find.byType(TextField), '08/10/1969');
1438
        expect(find.text(errorInvalidText!), findsNothing);
1439 1440 1441

        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();
1442
        expect(find.text(errorInvalidText!), findsOneWidget);
1443
      });
1444
    });
1445

1446
    testWidgetsWithLeakTracking('Invalid entered text shows error on autovalidate', (WidgetTester tester) async {
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
      // This is a regression test for https://github.com/flutter/flutter/issues/126397.
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
        final TextField field = textField(tester);
        field.controller!.clear();

        // Enter some text to trigger autovalidate.
        await tester.enterText(find.byType(TextField), 'xyz');
        await tester.tap(find.text('OK'));
        await tester.pumpAndSettle();

        // Invalid format validation error should be shown.
        expect(find.text('Invalid format.'), findsOneWidget);

        // Clear the text.
        field.controller!.clear();

        // Enter an invalid date that is too long while autovalidate is still on.
        await tester.enterText(find.byType(TextField), '10/05/2023666777889');
        await tester.pump();

        // Invalid format validation error should be shown.
        expect(find.text('Invalid format.'), findsOneWidget);
        // Should not throw an exception.
        expect(tester.takeException(), null);
      });
    });
1473 1474

    // This is a regression test for https://github.com/flutter/flutter/issues/131989.
1475
    testWidgetsWithLeakTracking('Dialog contents do not overflow when resized from landscape to portrait',
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
      (WidgetTester tester) async {
        addTearDown(tester.view.reset);
        // Initial window size is wide for landscape mode.
        tester.view.physicalSize = wideWindowSize;
        tester.view.devicePixelRatio = 1.0;

        await prepareDatePicker(tester, (Future<DateTime?> date) async {
          // Change window size to narrow for portrait mode.
          tester.view.physicalSize = narrowWindowSize;
          await tester.pump();
          expect(tester.takeException(), null);
        });
    });
1489
  });
1490

1491
  group('Semantics', () {
1492
    testWidgetsWithLeakTracking('calendar mode', (WidgetTester tester) async {
1493 1494
      final SemanticsHandle semantics = tester.ensureSemantics();

1495
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1496 1497 1498 1499 1500
        // Header
        expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
          label: 'SELECT DATE\nFri, Jan 15',
        ));

1501 1502
        expect(tester.getSemantics(find.text('3')), matchesSemantics(
          label: '3, Sunday, January 3, 2016, Today',
1503
          isButton: true,
1504 1505 1506 1507
          hasTapAction: true,
          isFocusable: true,
        ));

1508 1509
        // Input mode toggle button
        expect(tester.getSemantics(switchToInputIcon), matchesSemantics(
1510
          tooltip: 'Switch to input',
1511 1512 1513 1514 1515 1516 1517
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));

1518
        // The semantics of the CalendarDatePicker are tested in its tests.
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

        // 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,
        ));
      });
1538
      semantics.dispose();
1539
    });
1540

1541
    testWidgetsWithLeakTracking('input mode', (WidgetTester tester) async {
1542 1543 1544
      final SemanticsHandle semantics = tester.ensureSemantics();

      initialEntryMode = DatePickerEntryMode.input;
1545
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1546 1547 1548 1549 1550 1551 1552
        // Header
        expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
          label: 'SELECT DATE\nFri, Jan 15',
        ));

        // Input mode toggle button
        expect(tester.getSemantics(switchToCalendarIcon), matchesSemantics(
1553
          tooltip: 'Switch to calendar',
1554 1555 1556 1557 1558 1559 1560
          isButton: true,
          hasTapAction: true,
          isEnabled: true,
          hasEnabledState: true,
          isFocusable: true,
        ));

1561
        // The semantics of the InputDatePickerFormField are tested in its tests.
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

        // 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,
        ));
      });
1581
      semantics.dispose();
1582
    });
1583
  });
1584

1585
  group('Keyboard navigation', () {
1586
    testWidgetsWithLeakTracking('Can toggle to calendar entry mode', (WidgetTester tester) async {
1587
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1588 1589 1590 1591 1592 1593
        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);
1594
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
1595 1596 1597 1598 1599 1600 1601
        await tester.sendKeyEvent(LogicalKeyboardKey.space);
        await tester.pumpAndSettle();
        // Should be in the input mode
        expect(find.byType(TextField), findsOneWidget);
      });
    });

1602
    testWidgetsWithLeakTracking('Can toggle to year mode', (WidgetTester tester) async {
1603
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        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);
      });
    });

1614
    testWidgetsWithLeakTracking('Can navigate next/previous months', (WidgetTester tester) async {
1615
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
        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);
      });
    });
1641

1642
    testWidgetsWithLeakTracking('Can navigate date grid with arrow keys', (WidgetTester tester) async {
1643
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
        // 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));
      });
    });

1678
    testWidgetsWithLeakTracking('Navigating with arrow keys scrolls months', (WidgetTester tester) async {
1679
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
        // 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));
      });
    });

1726
    testWidgetsWithLeakTracking('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async {
1727
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
        // 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));
1760
      }, textDirection: TextDirection.rtl);
1761
    });
1762 1763
  });

1764
  group('Screen configurations', () {
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    // 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);

1780
    Future<void> showPicker(WidgetTester tester, Size size, [double textScaleFactor = 1.0]) async {
1781 1782 1783 1784
      tester.view.physicalSize = size;
      tester.view.devicePixelRatio = 1.0;
      addTearDown(tester.view.reset);

1785
      await prepareDatePicker(tester, (Future<DateTime?> date) async {
1786 1787
        await tester.tap(find.text('OK'));
      });
1788 1789 1790
      await tester.pumpAndSettle();
    }

1791
    testWidgetsWithLeakTracking('common screen size - portrait', (WidgetTester tester) async {
1792
      await showPicker(tester, kCommonScreenSizePortrait);
1793 1794 1795
      expect(tester.takeException(), isNull);
    });

1796
    testWidgetsWithLeakTracking('common screen size - landscape', (WidgetTester tester) async {
1797
      await showPicker(tester, kCommonScreenSizeLandscape);
1798 1799 1800
      expect(tester.takeException(), isNull);
    });

1801
    testWidgetsWithLeakTracking('common screen size - portrait - textScale 1.3', (WidgetTester tester) async {
1802
      await showPicker(tester, kCommonScreenSizePortrait, 1.3);
1803 1804 1805
      expect(tester.takeException(), isNull);
    });

1806
    testWidgetsWithLeakTracking('common screen size - landscape - textScale 1.3', (WidgetTester tester) async {
1807
      await showPicker(tester, kCommonScreenSizeLandscape, 1.3);
1808 1809 1810
      expect(tester.takeException(), isNull);
    });

1811
    testWidgetsWithLeakTracking('small screen size - portrait', (WidgetTester tester) async {
1812
      await showPicker(tester, kSmallScreenSizePortrait);
1813 1814 1815
      expect(tester.takeException(), isNull);
    });

1816
    testWidgetsWithLeakTracking('small screen size - landscape', (WidgetTester tester) async {
1817
      await showPicker(tester, kSmallScreenSizeLandscape);
1818 1819 1820
      expect(tester.takeException(), isNull);
    });

1821
    testWidgetsWithLeakTracking('small screen size - portrait -textScale 1.3', (WidgetTester tester) async {
1822
      await showPicker(tester, kSmallScreenSizePortrait, 1.3);
1823 1824 1825
      expect(tester.takeException(), isNull);
    });

1826
    testWidgetsWithLeakTracking('small screen size - landscape - textScale 1.3', (WidgetTester tester) async {
1827
      await showPicker(tester, kSmallScreenSizeLandscape, 1.3);
1828 1829 1830
      expect(tester.takeException(), isNull);
    });
  });
1831

1832
  group('showDatePicker avoids overlapping display features', () {
1833
    testWidgetsWithLeakTracking('positioning with anchorPoint', (WidgetTester tester) async {
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
      await tester.pumpWidget(
        MaterialApp(
          builder: (BuildContext context, Widget? child) {
            return MediaQuery(
              // Display has a vertical hinge down the middle
              data: const MediaQueryData(
                size: Size(800, 600),
                displayFeatures: <DisplayFeature>[
                  DisplayFeature(
                    bounds: Rect.fromLTRB(390, 0, 410, 600),
                    type: DisplayFeatureType.hinge,
                    state: DisplayFeatureState.unknown,
                  ),
                ],
              ),
              child: child!,
            );
          },
          home: const Center(child: Text('Test')),
        ),
      );

      final BuildContext context = tester.element(find.text('Test'));
      showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2018),
        lastDate: DateTime(2030),
        anchorPoint: const Offset(1000, 0),
      );
      await tester.pumpAndSettle();

      // Should take the right side of the screen
      expect(tester.getTopLeft(find.byType(DatePickerDialog)), const Offset(410.0, 0.0));
      expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(800.0, 600.0));
    });

1871
    testWidgetsWithLeakTracking('positioning with Directionality', (WidgetTester tester) async {
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
      await tester.pumpWidget(
        MaterialApp(
          builder: (BuildContext context, Widget? child) {
            return MediaQuery(
              // Display has a vertical hinge down the middle
              data: const MediaQueryData(
                size: Size(800, 600),
                displayFeatures: <DisplayFeature>[
                  DisplayFeature(
                    bounds: Rect.fromLTRB(390, 0, 410, 600),
                    type: DisplayFeatureType.hinge,
                    state: DisplayFeatureState.unknown,
                  ),
                ],
              ),
              child: Directionality(
                textDirection: TextDirection.rtl,
                child: child!,
              ),
            );
          },
          home: const Center(child: Text('Test')),
        ),
      );

      final BuildContext context = tester.element(find.text('Test'));
      showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2018),
        lastDate: DateTime(2030),
      );
      await tester.pumpAndSettle();

      // By default it should place the dialog on the right screen
      expect(tester.getTopLeft(find.byType(DatePickerDialog)), const Offset(410.0, 0.0));
      expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(800.0, 600.0));
    });

1911
    testWidgetsWithLeakTracking('positioning with defaults', (WidgetTester tester) async {
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
      await tester.pumpWidget(
        MaterialApp(
          builder: (BuildContext context, Widget? child) {
            return MediaQuery(
              // Display has a vertical hinge down the middle
              data: const MediaQueryData(
                size: Size(800, 600),
                displayFeatures: <DisplayFeature>[
                  DisplayFeature(
                    bounds: Rect.fromLTRB(390, 0, 410, 600),
                    type: DisplayFeatureType.hinge,
                    state: DisplayFeatureState.unknown,
                  ),
                ],
              ),
              child: child!,
            );
          },
          home: const Center(child: Text('Test')),
        ),
      );

      final BuildContext context = tester.element(find.text('Test'));
      showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2018),
        lastDate: DateTime(2030),
      );
      await tester.pumpAndSettle();

      // By default it should place the dialog on the left screen
      expect(tester.getTopLeft(find.byType(DatePickerDialog)), Offset.zero);
      expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(390.0, 600.0));
    });
  });

1949
  testWidgetsWithLeakTracking('DatePickerDialog is state restorable', (WidgetTester tester) async {
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    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);

1985
    // Select a different date.
1986 1987
    await tester.tap(find.text('30'));
    await tester.pumpAndSettle();
1988 1989 1990 1991 1992

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

    // Close the date picker.
1993 1994 1995 1996 1997 1998 1999 2000 2001
    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

2002
  testWidgetsWithLeakTracking('DatePickerDialog state restoration - DatePickerEntryMode', (WidgetTester tester) async {
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    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();

2038 2039
    // The date picker should be closed, the text value should be the same
    // as before.
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    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
2050

2051
  testWidgetsWithLeakTracking('Test Callback on Toggle of DatePicker Mode', (WidgetTester tester) async {
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
    prepareDatePicker(tester, (Future<DateTime?> date) async {
      await tester.tap(find.byIcon(Icons.edit));
      expect(currentMode, DatePickerEntryMode.input);
      await tester.pumpAndSettle();
      expect(find.byType(TextField), findsOneWidget);
      await tester.tap(find.byIcon(Icons.calendar_today));
      expect(currentMode, DatePickerEntryMode.calendar);
      await tester.pumpAndSettle();
      expect(find.byType(TextField), findsNothing);
    });
  });
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078

  group('Landscape input-only date picker headers use headlineSmall', () {
    // Regression test for https://github.com/flutter/flutter/issues/122056

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

    Future<void> showPicker(WidgetTester tester, Size size) async {
      addTearDown(tester.view.reset);
      tester.view.physicalSize = size;
      tester.view.devicePixelRatio = 1.0;
      initialEntryMode = DatePickerEntryMode.input;
      await prepareDatePicker(tester, (Future<DateTime?> date) async { }, useMaterial3: true);
    }

2079
    testWidgetsWithLeakTracking('portrait', (WidgetTester tester) async {
2080 2081 2082 2083 2084 2085
      await showPicker(tester, kCommonScreenSizePortrait);
      expect(tester.widget<Text>(find.text('Fri, Jan 15')).style?.fontSize, 32);
      await tester.tap(find.text('Cancel'));
      await tester.pumpAndSettle();
    });

2086
    testWidgetsWithLeakTracking('landscape', (WidgetTester tester) async {
2087 2088 2089 2090 2091 2092
      await showPicker(tester, kCommonScreenSizeLandscape);
      expect(tester.widget<Text>(find.text('Fri, Jan 15')).style?.fontSize, 24);
      await tester.tap(find.text('Cancel'));
      await tester.pumpAndSettle();
    });
  });
2093 2094

  group('Material 2', () {
2095 2096 2097
    // These tests are only relevant for Material 2. Once Material 2
    // support is deprecated and the APIs are removed, these tests
    // can be deleted.
2098 2099

    group('showDatePicker Dialog', () {
2100
      testWidgetsWithLeakTracking('Default dialog size', (WidgetTester tester) async {
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
        Future<void> showPicker(WidgetTester tester, Size size) async {
          tester.view.physicalSize = size;
          tester.view.devicePixelRatio = 1.0;
          addTearDown(tester.view.reset);
          await prepareDatePicker(tester, (Future<DateTime?> date) async {});
        }
        const Size wideWindowSize = Size(1920.0, 1080.0);
        const Size narrowWindowSize = Size(1070.0, 1770.0);
        const Size calendarLandscapeDialogSize = Size(496.0, 346.0);
        const Size calendarPortraitDialogSizeM2 = Size(330.0, 518.0);

        // Test landscape layout.
        await showPicker(tester, wideWindowSize);

        Size dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
        expect(dialogContainerSize, calendarLandscapeDialogSize);

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

        // Test portrait layout.
        await showPicker(tester, narrowWindowSize);

        dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
        expect(dialogContainerSize, calendarPortraitDialogSizeM2);
      });

2129
      testWidgetsWithLeakTracking('Default dialog properties', (WidgetTester tester) async {
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
        final ThemeData theme = ThemeData(useMaterial3: false);
        await prepareDatePicker(tester, (Future<DateTime?> date) async {
          final Material dialogMaterial = tester.widget<Material>(
            find.descendant(of: find.byType(Dialog),
            matching: find.byType(Material),
          ).first);

          expect(dialogMaterial.color, theme.colorScheme.surface);
          expect(dialogMaterial.shadowColor, theme.shadowColor);
          expect(dialogMaterial.elevation, 24.0);
          expect(
            dialogMaterial.shape,
            const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
          );
          expect(dialogMaterial.clipBehavior, Clip.antiAlias);


          final Dialog dialog = tester.widget<Dialog>(find.byType(Dialog));
          expect(dialog.insetPadding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0));
        }, useMaterial3: theme.useMaterial3);
      });
    });

    group('Input mode', () {
      setUp(() {
        firstDate = DateTime(2015);
        lastDate = DateTime(2017, DateTime.december, 31);
        initialDate = DateTime(2016, DateTime.january, 15);
        initialEntryMode = DatePickerEntryMode.input;
      });

2161
      testWidgetsWithLeakTracking('Default InputDecoration', (WidgetTester tester) async {
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
        await prepareDatePicker(tester, (Future<DateTime?> date) async {
          final InputDecoration decoration = tester.widget<TextField>(
            find.byType(TextField)).decoration!;
          expect(decoration.border, const UnderlineInputBorder());
          expect(decoration.filled, false);
          expect(decoration.hintText, 'mm/dd/yyyy');
          expect(decoration.labelText, 'Enter Date');
          expect(decoration.errorText, null);
        });
      });
    });
  });
2174 2175 2176 2177 2178
}

class _RestorableDatePickerDialogTestWidget extends StatefulWidget {
  const _RestorableDatePickerDialogTestWidget({
    this.datePickerEntryMode = DatePickerEntryMode.calendar,
2179
  });
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199

  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,
2200
        },
2201 2202 2203 2204
      );
    },
  );

2205 2206 2207 2208 2209 2210 2211
  @override
  void dispose() {
    _selectedDate.dispose();
    _restorableDatePickerRouteFuture.dispose();
    super.dispose();
  }

2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
  @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; });
    }
  }

2224
  @pragma('vm:entry-point')
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
  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),
2237 2238
          firstDate: DateTime(2021),
          lastDate: DateTime(2022),
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        );
      },
    );
  }

  @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),
          ],
        ),
      ),
    );
  }
2265 2266
}

2267
class _DatePickerObserver extends NavigatorObserver {
2268 2269 2270
  int datePickerCount = 0;

  @override
2271
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
2272
    if (route is DialogRoute) {
2273 2274 2275 2276
      datePickerCount++;
    }
    super.didPush(route, previousRoute);
  }
2277 2278 2279 2280 2281 2282 2283 2284

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (route is DialogRoute) {
      datePickerCount--;
    }
    super.didPop(route, previousRoute);
  }
Ian Hickson's avatar
Ian Hickson committed
2285
}