time_picker_test.dart 82.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Hans Muller's avatar
Hans Muller 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
@TestOn('!chrome')
6 7
library;

8
import 'dart:math' as math;
9 10
import 'dart:ui';

Hans Muller's avatar
Hans Muller committed
11
import 'package:flutter/material.dart';
Yegor's avatar
Yegor committed
12
import 'package:flutter/rendering.dart';
Hans Muller's avatar
Hans Muller committed
13
import 'package:flutter_test/flutter_test.dart';
14
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
Hans Muller's avatar
Hans Muller committed
15

16
import '../widgets/semantics_tester.dart';
17 18
import 'feedback_tester.dart';

19
void main() {
20 21 22 23 24 25 26
  const String okString = 'OK';
  const String amString = 'AM';
  const String pmString = 'PM';
  Material getMaterialFromDialog(WidgetTester tester) {
    return tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first);
  }

27
  testWidgetsWithLeakTracking('Material2 - Dialog size - dial mode', (WidgetTester tester) async {
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    addTearDown(tester.view.reset);

    const Size timePickerPortraitSize =  Size(310, 468);
    const Size timePickerLandscapeSize = Size(524, 342);
    const Size timePickerLandscapeSizeM2 = Size(508, 300);
    const EdgeInsets padding = EdgeInsets.fromLTRB(8, 18, 8, 8);
    double width;
    double height;

    // portrait
    tester.view.physicalSize = const Size(800, 800.5);
    tester.view.devicePixelRatio = 1;
    await mediaQueryBoilerplate(tester, materialType: MaterialType.material2);

    width = timePickerPortraitSize.width + padding.horizontal;
    height = timePickerPortraitSize.height + padding.vertical;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );

    await tester.tap(find.text(okString)); // dismiss the dialog
    await tester.pumpAndSettle();

    // landscape
    tester.view.physicalSize = const Size(800.5, 800);
    tester.view.devicePixelRatio = 1;
    await mediaQueryBoilerplate(
      tester,
      alwaysUse24HourFormat: true,
      materialType: MaterialType.material2,
    );

    width =  timePickerLandscapeSize.width + padding.horizontal;
    height = timePickerLandscapeSizeM2.height + padding.vertical;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );
  });

69
  testWidgetsWithLeakTracking('Material2 - Dialog size - input mode', (WidgetTester tester) async {
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    const TimePickerEntryMode entryMode = TimePickerEntryMode.input;
    const Size timePickerInputSize = Size(312, 216);
    const Size dayPeriodPortraitSize = Size(52, 80);
    const EdgeInsets padding = EdgeInsets.fromLTRB(8, 18, 8, 8);
    final double height = timePickerInputSize.height + padding.vertical;
    double width;

    await mediaQueryBoilerplate(
      tester,
      entryMode: entryMode,
      materialType: MaterialType.material2,
    );

    width = timePickerInputSize.width + padding.horizontal;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );

    await tester.tap(find.text(okString)); // dismiss the dialog
    await tester.pumpAndSettle();

    await mediaQueryBoilerplate(
      tester,
      alwaysUse24HourFormat: true,
      entryMode: entryMode,
      materialType: MaterialType.material2,
    );
    width = timePickerInputSize.width - dayPeriodPortraitSize.width - 12 + padding.horizontal + 16;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );
  });

105
  testWidgetsWithLeakTracking('Material2 - respects MediaQueryData.alwaysUse24HourFormat == true', (WidgetTester tester) async {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, materialType: MaterialType.material2);

    final List<String> labels00To22 = List<String>.generate(12, (int index) {
      return (index * 2).toString().padLeft(2, '0');
    });
    final CustomPaint dialPaint = tester.widget(findDialPaint);
    final dynamic dialPainter = dialPaint.painter;
    // ignore: avoid_dynamic_calls
    final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
    // ignore: avoid_dynamic_calls
    expect(primaryLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels00To22);

    // ignore: avoid_dynamic_calls
    final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
    // ignore: avoid_dynamic_calls
    expect(selectedLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels00To22);
  });

124
  testWidgetsWithLeakTracking('Material3 - Dialog size - dial mode', (WidgetTester tester) async {
125 126 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 153 154 155 156 157 158 159 160 161 162 163 164
    addTearDown(tester.view.reset);

    const Size timePickerPortraitSize =  Size(310, 468);
    const Size timePickerLandscapeSize = Size(524, 342);
    const EdgeInsets padding = EdgeInsets.all(24.0);
    double width;
    double height;

    // portrait
    tester.view.physicalSize = const Size(800, 800.5);
    tester.view.devicePixelRatio = 1;
    await mediaQueryBoilerplate(tester, materialType: MaterialType.material3);

    width = timePickerPortraitSize.width + padding.horizontal;
    height = timePickerPortraitSize.height + padding.vertical;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );

    await tester.tap(find.text(okString)); // dismiss the dialog
    await tester.pumpAndSettle();

    // landscape
    tester.view.physicalSize = const Size(800.5, 800);
    tester.view.devicePixelRatio = 1;
    await mediaQueryBoilerplate(
      tester,
      alwaysUse24HourFormat: true,
      materialType: MaterialType.material3,
    );

    width =  timePickerLandscapeSize.width + padding.horizontal;
    height = timePickerLandscapeSize.height + padding.vertical;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );
  });

165
  testWidgetsWithLeakTracking('Material3 - Dialog size - input mode', (WidgetTester tester) async {
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    final ThemeData theme = ThemeData(useMaterial3: true);
    const TimePickerEntryMode entryMode = TimePickerEntryMode.input;
    const double textScaleFactor = 1.0;
    const Size timePickerMinInputSize = Size(312, 216);
    const Size dayPeriodPortraitSize = Size(52, 80);
    const EdgeInsets padding = EdgeInsets.all(24.0);
    final double height = timePickerMinInputSize.height * textScaleFactor + padding.vertical;
    double width;

    await mediaQueryBoilerplate(
      tester,
      entryMode: entryMode,
      materialType: MaterialType.material3,
    );

    width = timePickerMinInputSize.width - (theme.useMaterial3 ? 32 : 0) + padding.horizontal;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );

    await tester.tap(find.text(okString)); // dismiss the dialog
    await tester.pumpAndSettle();

    await mediaQueryBoilerplate(
      tester,
      alwaysUse24HourFormat: true,
      entryMode: entryMode,
      materialType: MaterialType.material3,
    );

    width = timePickerMinInputSize.width - dayPeriodPortraitSize.width - 12 + padding.horizontal;
    expect(
      tester.getSize(find.byWidget(getMaterialFromDialog(tester))),
      Size(width, height),
    );
  });

204
  testWidgetsWithLeakTracking('Material3 - respects MediaQueryData.alwaysUse24HourFormat == true', (WidgetTester tester) async {
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, materialType: MaterialType.material3);

    final List<String> labels00To23 = List<String>.generate(24, (int index) {
      return index == 0 ? '00' : index.toString();
    });
    final List<bool> inner0To23 = List<bool>.generate(24, (int index) => index >= 12);

    final CustomPaint dialPaint = tester.widget(findDialPaint);
    final dynamic dialPainter = dialPaint.painter;
    // ignore: avoid_dynamic_calls
    final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
    // ignore: avoid_dynamic_calls
    expect(primaryLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels00To23);
    // ignore: avoid_dynamic_calls
    expect(primaryLabels.map<bool>((dynamic tp) => tp.inner as bool), inner0To23);

    // ignore: avoid_dynamic_calls
    final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
    // ignore: avoid_dynamic_calls
    expect(selectedLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels00To23);
    // ignore: avoid_dynamic_calls
    expect(selectedLabels.map<bool>((dynamic tp) => tp.inner as bool), inner0To23);
  });
228

229
  testWidgetsWithLeakTracking('Material3 - Dial background uses correct default color', (WidgetTester tester) async {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    ThemeData theme = ThemeData(useMaterial3: true);
    Widget buildTimePicker(ThemeData themeData) {
      return MaterialApp(
        theme: themeData,
        home: Material(
          child: Center(
            child: Builder(
              builder: (BuildContext context) {
                return ElevatedButton(
                  child: const Text('X'),
                  onPressed: () {
                    showTimePicker(
                      context: context,
                      initialTime: const TimeOfDay(hour: 7, minute: 0),
                    );
                  },
                );
              },
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildTimePicker(theme));

    // Open the time picker dialog.
    await tester.tap(find.text('X'));
    await tester.pumpAndSettle();

    // Test default dial background color.
    RenderBox dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
    expect(
      dial,
      paints
        ..circle(color: theme.colorScheme.surfaceVariant) // Dial background color.
        ..circle(color: Color(theme.colorScheme.primary.value)), // Dial hand color.
    );

    await tester.tap(find.text(okString)); // dismiss the dialog
    await tester.pumpAndSettle();

    // Test dial background color when theme color scheme is changed.
    theme = theme.copyWith(
      colorScheme: theme.colorScheme.copyWith(
        surfaceVariant: const Color(0xffff0000),
      ),
    );
    await tester.pumpWidget(buildTimePicker(theme));

    // Open the time picker dialog.
    await tester.tap(find.text('X'));
    await tester.pumpAndSettle();

    dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
    expect(
      dial,
      paints
        ..circle(color: const Color(0xffff0000)) // Dial background color.
        ..circle(color: Color(theme.colorScheme.primary.value)), // Dial hand color.
    );
  });

293
  for (final MaterialType materialType in MaterialType.values) {
294
    group('Dial (${materialType.name})', () {
295
      testWidgetsWithLeakTracking('tap-select an hour', (WidgetTester tester) async {
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        TimeOfDay? result;

        Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time;
        }, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy - 50)); // 12:00 AM
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 0, minute: 0)));

        center = (await startPicker(tester, (TimeOfDay? time) {
          result = time;
        }, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx + 50, center.dy));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 3, minute: 0)));

        center = (await startPicker(tester, (TimeOfDay? time) {
          result = time;
        }, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy + 50));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 0)));

        center = (await startPicker(tester, (TimeOfDay? time) {
          result = time;
        }, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy + 50));
        await tester.tapAt(Offset(center.dx - 50, center.dy));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 9, minute: 0)));
      });

328
      testWidgetsWithLeakTracking('drag-select an hour', (WidgetTester tester) async {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 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 382 383
        late TimeOfDay result;

        final Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, materialType: materialType))!;
        final Offset hour0 = Offset(center.dx, center.dy - 50); // 12:00 AM
        final Offset hour3 = Offset(center.dx + 50, center.dy);
        final Offset hour6 = Offset(center.dx, center.dy + 50);
        final Offset hour9 = Offset(center.dx - 50, center.dy);

        TestGesture gesture;

        gesture = await tester.startGesture(hour3);
        await gesture.moveBy(hour0 - hour3);
        await gesture.up();
        await finishPicker(tester);
        expect(result.hour, 0);

        expect(
          await startPicker(tester, (TimeOfDay? time) {
            result = time!;
          }, materialType: materialType),
          equals(center),
        );
        gesture = await tester.startGesture(hour0);
        await gesture.moveBy(hour3 - hour0);
        await gesture.up();
        await finishPicker(tester);
        expect(result.hour, 3);

        expect(
          await startPicker(tester, (TimeOfDay? time) {
            result = time!;
          }, materialType: materialType),
          equals(center),
        );
        gesture = await tester.startGesture(hour3);
        await gesture.moveBy(hour6 - hour3);
        await gesture.up();
        await finishPicker(tester);
        expect(result.hour, equals(6));

        expect(
          await startPicker(tester, (TimeOfDay? time) {
            result = time!;
          }, materialType: materialType),
          equals(center),
        );
        gesture = await tester.startGesture(hour6);
        await gesture.moveBy(hour9 - hour6);
        await gesture.up();
        await finishPicker(tester);
        expect(result.hour, equals(9));
      });

384
      testWidgetsWithLeakTracking('tap-select switches from hour to minute', (WidgetTester tester) async {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        late TimeOfDay result;

        final Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, materialType: materialType))!;
        final Offset hour6 = Offset(center.dx, center.dy + 50); // 6:00
        final Offset min45 = Offset(center.dx - 50, center.dy); // 45 mins (or 9:00 hours)

        await tester.tapAt(hour6);
        await tester.pump(const Duration(milliseconds: 50));
        await tester.tapAt(min45);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 45)));
      });

400
      testWidgetsWithLeakTracking('drag-select switches from hour to minute', (WidgetTester tester) async {
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        late TimeOfDay result;

        final Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, materialType: materialType))!;
        final Offset hour3 = Offset(center.dx + 50, center.dy);
        final Offset hour6 = Offset(center.dx, center.dy + 50);
        final Offset hour9 = Offset(center.dx - 50, center.dy);

        TestGesture gesture = await tester.startGesture(hour6);
        await gesture.moveBy(hour9 - hour6);
        await gesture.up();
        await tester.pump(const Duration(milliseconds: 50));
        gesture = await tester.startGesture(hour6);
        await gesture.moveBy(hour3 - hour6);
        await gesture.up();
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 9, minute: 15)));
      });

421
      testWidgetsWithLeakTracking('tap-select rounds down to nearest 5 minute increment', (WidgetTester tester) async {
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        late TimeOfDay result;

        final Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, materialType: materialType))!;
        final Offset hour6 = Offset(center.dx, center.dy + 50); // 6:00
        final Offset min46 = Offset(center.dx - 50, center.dy - 5); // 46 mins

        await tester.tapAt(hour6);
        await tester.pump(const Duration(milliseconds: 50));
        await tester.tapAt(min46);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 45)));
      });

437
      testWidgetsWithLeakTracking('tap-select rounds up to nearest 5 minute increment', (WidgetTester tester) async {
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
        late TimeOfDay result;

        final Offset center = (await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, materialType: materialType))!;
        final Offset hour6 = Offset(center.dx, center.dy + 50); // 6:00
        final Offset min48 = Offset(center.dx - 50, center.dy - 15); // 48 mins

        await tester.tapAt(hour6);
        await tester.pump(const Duration(milliseconds: 50));
        await tester.tapAt(min48);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 50)));
      });
    });

    group('Dial Haptic Feedback (${materialType.name})', () {
      const Duration kFastFeedbackInterval = Duration(milliseconds: 10);
      const Duration kSlowFeedbackInterval = Duration(milliseconds: 200);
      late FeedbackTester feedback;

      setUp(() {
        feedback = FeedbackTester();
      });

      tearDown(() {
        feedback.dispose();
      });

467
      testWidgetsWithLeakTracking('tap-select vibrates once', (WidgetTester tester) async {
468 469 470 471 472 473
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy - 50));
        await finishPicker(tester);
        expect(feedback.hapticCount, 1);
      });

474
      testWidgetsWithLeakTracking('quick successive tap-selects vibrate once', (WidgetTester tester) async {
475 476 477 478 479 480 481 482
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy - 50));
        await tester.pump(kFastFeedbackInterval);
        await tester.tapAt(Offset(center.dx, center.dy + 50));
        await finishPicker(tester);
        expect(feedback.hapticCount, 1);
      });

483
      testWidgetsWithLeakTracking('slow successive tap-selects vibrate once per tap', (WidgetTester tester) async {
484 485 486 487 488 489 490 491 492 493
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        await tester.tapAt(Offset(center.dx, center.dy - 50));
        await tester.pump(kSlowFeedbackInterval);
        await tester.tapAt(Offset(center.dx, center.dy + 50));
        await tester.pump(kSlowFeedbackInterval);
        await tester.tapAt(Offset(center.dx, center.dy - 50));
        await finishPicker(tester);
        expect(feedback.hapticCount, 3);
      });

494
      testWidgetsWithLeakTracking('drag-select vibrates once', (WidgetTester tester) async {
495 496 497 498 499 500 501 502 503 504 505
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        final Offset hour0 = Offset(center.dx, center.dy - 50);
        final Offset hour3 = Offset(center.dx + 50, center.dy);

        final TestGesture gesture = await tester.startGesture(hour3);
        await gesture.moveBy(hour0 - hour3);
        await gesture.up();
        await finishPicker(tester);
        expect(feedback.hapticCount, 1);
      });

506
      testWidgetsWithLeakTracking('quick drag-select vibrates once', (WidgetTester tester) async {
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        final Offset hour0 = Offset(center.dx, center.dy - 50);
        final Offset hour3 = Offset(center.dx + 50, center.dy);

        final TestGesture gesture = await tester.startGesture(hour3);
        await gesture.moveBy(hour0 - hour3);
        await tester.pump(kFastFeedbackInterval);
        await gesture.moveBy(hour3 - hour0);
        await tester.pump(kFastFeedbackInterval);
        await gesture.moveBy(hour0 - hour3);
        await gesture.up();
        await finishPicker(tester);
        expect(feedback.hapticCount, 1);
      });

522
      testWidgetsWithLeakTracking('slow drag-select vibrates once', (WidgetTester tester) async {
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        final Offset center = (await startPicker(tester, (TimeOfDay? time) {}, materialType: materialType))!;
        final Offset hour0 = Offset(center.dx, center.dy - 50);
        final Offset hour3 = Offset(center.dx + 50, center.dy);

        final TestGesture gesture = await tester.startGesture(hour3);
        await gesture.moveBy(hour0 - hour3);
        await tester.pump(kSlowFeedbackInterval);
        await gesture.moveBy(hour3 - hour0);
        await tester.pump(kSlowFeedbackInterval);
        await gesture.moveBy(hour0 - hour3);
        await gesture.up();
        await finishPicker(tester);
        expect(feedback.hapticCount, 3);
      });
    });

    group('Dialog (${materialType.name})', () {
540
      testWidgetsWithLeakTracking('Material2 - Widgets have correct label capitalization', (WidgetTester tester) async {
541 542 543 544 545
        await startPicker(tester, (TimeOfDay? time) {}, materialType: MaterialType.material2);
        expect(find.text('SELECT TIME'), findsOneWidget);
        expect(find.text('CANCEL'), findsOneWidget);
      });

546
      testWidgetsWithLeakTracking('Material3 - Widgets have correct label capitalization', (WidgetTester tester) async {
547 548 549 550 551
        await startPicker(tester, (TimeOfDay? time) {}, materialType: MaterialType.material3);
        expect(find.text('Select time'), findsOneWidget);
        expect(find.text('Cancel'), findsOneWidget);
      });

552
      testWidgetsWithLeakTracking('Material2 - Widgets have correct label capitalization in input mode', (WidgetTester tester) async {
553 554 555 556 557
        await startPicker(tester, (TimeOfDay? time) {},
          entryMode: TimePickerEntryMode.input, materialType: MaterialType.material2
        );
        expect(find.text('ENTER TIME'), findsOneWidget);
        expect(find.text('CANCEL'), findsOneWidget);
558 559
      });

560
      testWidgetsWithLeakTracking('Material3 - Widgets have correct label capitalization in input mode', (WidgetTester tester) async {
561
        await startPicker(tester, (TimeOfDay? time) {},
562 563 564 565
          entryMode: TimePickerEntryMode.input, materialType: MaterialType.material3
        );
        expect(find.text('Enter time'), findsOneWidget);
        expect(find.text('Cancel'), findsOneWidget);
566 567
      });

568
      testWidgetsWithLeakTracking('respects MediaQueryData.alwaysUse24HourFormat == false', (WidgetTester tester) async {
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
        await mediaQueryBoilerplate(tester, materialType: materialType);
        const List<String> labels12To11 = <String>['12', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];

        final CustomPaint dialPaint = tester.widget(findDialPaint);
        final dynamic dialPainter = dialPaint.painter;
        // ignore: avoid_dynamic_calls
        final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
        // ignore: avoid_dynamic_calls
        expect(primaryLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels12To11);

        // ignore: avoid_dynamic_calls
        final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
        // ignore: avoid_dynamic_calls
        expect(selectedLabels.map<String>((dynamic tp) => tp.painter.text.text as String), labels12To11);
      });

585
      testWidgetsWithLeakTracking('when change orientation, should reflect in render objects', (WidgetTester tester) async {
586 587
        addTearDown(tester.view.reset);

588
        // portrait
589 590
        tester.view.physicalSize = const Size(800, 800.5);
        tester.view.devicePixelRatio = 1;
591 592 593 594 595 596 597 598
        await mediaQueryBoilerplate(tester, materialType: materialType);

        RenderObject render = tester.renderObject(
          find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodInputPadding'),
        );
        expect((render as dynamic).orientation, Orientation.portrait); // ignore: avoid_dynamic_calls

        // landscape
599 600
        tester.view.physicalSize = const Size(800.5, 800);
        tester.view.devicePixelRatio = 1;
601 602 603 604 605 606 607 608
        await mediaQueryBoilerplate(tester, tapButton: false, materialType: materialType);

        render = tester.renderObject(
          find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodInputPadding'),
        );
        expect((render as dynamic).orientation, Orientation.landscape); // ignore: avoid_dynamic_calls
      });

609
      testWidgetsWithLeakTracking('setting orientation should override MediaQuery orientation', (WidgetTester tester) async {
610 611
        addTearDown(tester.view.reset);

612
        // portrait media query
613 614
        tester.view.physicalSize = const Size(800, 800.5);
        tester.view.devicePixelRatio = 1;
615 616 617 618 619 620 621 622
        await mediaQueryBoilerplate(tester, orientation: Orientation.landscape, materialType: materialType);

        final RenderObject render = tester.renderObject(
          find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodInputPadding'),
        );
        expect((render as dynamic).orientation, Orientation.landscape); // ignore: avoid_dynamic_calls
      });

623
      testWidgetsWithLeakTracking('builder parameter', (WidgetTester tester) async {
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
        Widget buildFrame(TextDirection textDirection) {
          return MaterialApp(
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () {
                        showTimePicker(
                          context: context,
                          initialTime: const TimeOfDay(hour: 7, minute: 0),
                          builder: (BuildContext context, Widget? child) {
                            return Directionality(
                              textDirection: textDirection,
                              child: child!,
                            );
                          },
                        );
                      },
                    );
                  },
                ),
              ),
            ),
          );
        }

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

        await tester.tap(find.text(okString)); // 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'
667
        // button and the right edge of the 800 wide view.
668 669 670
        expect(tester.getBottomLeft(find.text(okString)).dx, 800 - ltrOkRight);
      });

671 672 673 674 675 676 677
      group('Barrier dismissible', () {
        late PickerObserver rootObserver;

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

678
        testWidgetsWithLeakTracking('Barrier is dismissible with default parameter', (WidgetTester tester) async {
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
          await tester.pumpWidget(
            MaterialApp(
              navigatorObservers: <NavigatorObserver>[rootObserver],
              home: Material(
                child: Center(
                  child: Builder(
                    builder: (BuildContext context) {
                      return ElevatedButton(
                        child: const Text('X'),
                        onPressed: () =>
                            showTimePicker(
                              context: context,
                              initialTime: const TimeOfDay(hour: 7, minute: 0),
                            ),
                      );
                    },
                  ),
                ),
              ),
            ),
          );

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

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

712
        testWidgetsWithLeakTracking('Barrier is not dismissible with barrierDismissible is false', (WidgetTester tester) async {
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
          await tester.pumpWidget(
            MaterialApp(
              navigatorObservers: <NavigatorObserver>[rootObserver],
              home: Material(
                child: Center(
                  child: Builder(
                    builder: (BuildContext context) {
                      return ElevatedButton(
                        child: const Text('X'),
                        onPressed: () =>
                            showTimePicker(
                              context: context,
                              barrierDismissible: false,
                              initialTime: const TimeOfDay(hour: 7, minute: 0),
                            ),
                      );
                    },
                  ),
                ),
              ),
            ),
          );

          // Open the dialog.
          await tester.tap(find.byType(ElevatedButton));
          await tester.pumpAndSettle();
          expect(rootObserver.pickerCount, 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.pickerCount, 1);
        });
      });

748
      testWidgetsWithLeakTracking('Barrier color', (WidgetTester tester) async {
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 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
        await tester.pumpWidget(
          MaterialApp(
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () => showTimePicker(
                        context: context,
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        );

        // 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: () => showTimePicker(
                        context: context,
                        barrierColor: Colors.pink,
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        );

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

804
      testWidgetsWithLeakTracking('Barrier Label', (WidgetTester tester) async {
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        await tester.pumpWidget(
          MaterialApp(
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () => showTimePicker(
                        context: context,
                        barrierLabel: 'Custom Label',
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        );

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

832
      testWidgetsWithLeakTracking('uses root navigator by default', (WidgetTester tester) async {
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
        final PickerObserver rootObserver = PickerObserver();
        final PickerObserver nestedObserver = PickerObserver();

        await tester.pumpWidget(MaterialApp(
          navigatorObservers: <NavigatorObserver>[rootObserver],
          home: Navigator(
            observers: <NavigatorObserver>[nestedObserver],
            onGenerateRoute: (RouteSettings settings) {
              return MaterialPageRoute<dynamic>(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    onPressed: () {
                      showTimePicker(
                        context: context,
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                      );
                    },
                    child: const Text('Show Picker'),
                  );
                },
              );
            },
          ),
        ));

        // Open the dialog.
        await tester.tap(find.byType(ElevatedButton));

        expect(rootObserver.pickerCount, 1);
        expect(nestedObserver.pickerCount, 0);
      });

865
      testWidgetsWithLeakTracking('uses nested navigator if useRootNavigator is false', (WidgetTester tester) async {
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
        final PickerObserver rootObserver = PickerObserver();
        final PickerObserver nestedObserver = PickerObserver();

        await tester.pumpWidget(MaterialApp(
          navigatorObservers: <NavigatorObserver>[rootObserver],
          home: Navigator(
            observers: <NavigatorObserver>[nestedObserver],
            onGenerateRoute: (RouteSettings settings) {
              return MaterialPageRoute<dynamic>(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    onPressed: () {
                      showTimePicker(
                        context: context,
                        useRootNavigator: false,
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                      );
                    },
                    child: const Text('Show Picker'),
                  );
                },
              );
            },
          ),
        ));

        // Open the dialog.
        await tester.tap(find.byType(ElevatedButton));

        expect(rootObserver.pickerCount, 0);
        expect(nestedObserver.pickerCount, 1);
      });

899
      testWidgetsWithLeakTracking('optional text parameters are utilized', (WidgetTester tester) async {
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        const String cancelText = 'Custom Cancel';
        const String confirmText = 'Custom OK';
        const String helperText = 'Custom Help';
        await tester.pumpWidget(MaterialApp(
          home: Material(
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  return ElevatedButton(
                    child: const Text('X'),
                    onPressed: () async {
                      await showTimePicker(
                        context: context,
                        initialTime: const TimeOfDay(hour: 7, minute: 0),
                        cancelText: cancelText,
                        confirmText: confirmText,
                        helpText: helperText,
                      );
                    },
                  );
                },
              ),
            ),
          ),
        ));

        // Open the picker.
        await tester.tap(find.text('X'));
        await tester.pumpAndSettle(const Duration(seconds: 1));

        expect(find.text(cancelText), findsOneWidget);
        expect(find.text(confirmText), findsOneWidget);
        expect(find.text(helperText), findsOneWidget);
      });

935
      testWidgetsWithLeakTracking('Material2 - OK Cancel button and helpText layout', (WidgetTester tester) async {
936 937
        const String selectTimeString = 'SELECT TIME';
        const String cancelString = 'CANCEL';
938 939
        Widget buildFrame(TextDirection textDirection) {
          return MaterialApp(
940
            theme: ThemeData(useMaterial3: false),
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () {
                        showTimePicker(
                          context: context,
                          initialTime: const TimeOfDay(hour: 7, minute: 0),
                          builder: (BuildContext context, Widget? child) {
                            return Directionality(
                              textDirection: textDirection,
                              child: child!,
                            );
                          },
                        );
                      },
                    );
                  },
                ),
              ),
            ),
          );
        }

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

971 972
        expect(tester.getTopLeft(find.text(selectTimeString)), equals(const Offset(154, 155)));
        expect(tester.getBottomRight(find.text(selectTimeString)), equals(
973
          const Offset(280.5, 165),
974 975 976 977
        ));
        expect(tester.getBottomRight(find.text(okString)).dx, 644);
        expect(tester.getBottomLeft(find.text(okString)).dx, 616);
        expect(tester.getBottomRight(find.text(cancelString)).dx, 582);
978 979 980 981 982 983 984 985

        await tester.tap(find.text(okString));
        await tester.pumpAndSettle();

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

986
        expect(tester.getTopLeft(find.text(selectTimeString)), equals(
987
          const Offset(519.5, 155),
988 989 990 991 992 993 994 995 996 997
        ));
        expect(tester.getBottomRight(find.text(selectTimeString)), equals(const Offset(646, 165)));
        expect(tester.getBottomLeft(find.text(okString)).dx, 156);
        expect(tester.getBottomRight(find.text(okString)).dx, 184);
        expect(tester.getBottomLeft(find.text(cancelString)).dx, 218);

        await tester.tap(find.text(okString));
        await tester.pumpAndSettle();
      });

998
      testWidgetsWithLeakTracking('Material3 - OK Cancel button and helpText layout', (WidgetTester tester) async {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        const String selectTimeString = 'Select time';
        const String cancelString = 'Cancel';
        Widget buildFrame(TextDirection textDirection) {
          return MaterialApp(
            theme: ThemeData(useMaterial3: true),
            home: Material(
              child: Center(
                child: Builder(
                  builder: (BuildContext context) {
                    return ElevatedButton(
                      child: const Text('X'),
                      onPressed: () {
                        showTimePicker(
                          context: context,
                          initialTime: const TimeOfDay(hour: 7, minute: 0),
                          builder: (BuildContext context, Widget? child) {
                            return Directionality(
                              textDirection: textDirection,
                              child: child!,
                            );
                          },
                        );
                      },
                    );
                  },
                ),
              ),
            ),
          );
1028 1029
        }

1030 1031 1032 1033 1034
        await tester.pumpWidget(buildFrame(TextDirection.ltr));
        await tester.tap(find.text('X'));
        await tester.pumpAndSettle();

        expect(tester.getTopLeft(find.text(selectTimeString)), equals(const Offset(138, 129)));
1035 1036 1037 1038 1039 1040 1041 1042
        expect(
          tester.getBottomRight(find.text(selectTimeString)),
          const Offset(294.75, 149.0),
        );
        expect(
          tester.getBottomLeft(find.text(okString)).dx,
          moreOrLessEquals(615.9, epsilon: 0.001),
        );
1043 1044 1045 1046 1047 1048 1049 1050 1051
        expect(tester.getBottomRight(find.text(cancelString)).dx, 578);

        await tester.tap(find.text(okString));
        await tester.pumpAndSettle();

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

1052 1053 1054 1055
        expect(
          tester.getTopLeft(find.text(selectTimeString)),
          equals(const Offset(505.25, 129.0)),
        );
1056
        expect(tester.getBottomRight(find.text(selectTimeString)), equals(const Offset(662, 149)));
1057 1058 1059 1060 1061 1062 1063 1064
        expect(
          tester.getBottomLeft(find.text(okString)).dx,
          moreOrLessEquals(155.9, epsilon: 0.001),
        );
        expect(
          tester.getBottomRight(find.text(okString)).dx,
          moreOrLessEquals(184.1, epsilon: 0.001),
        );
1065 1066
        expect(tester.getBottomLeft(find.text(cancelString)).dx, 222);

1067 1068 1069 1070
        await tester.tap(find.text(okString));
        await tester.pumpAndSettle();
      });

1071
      testWidgetsWithLeakTracking('text scale affects certain elements and not others', (WidgetTester tester) async {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        await mediaQueryBoilerplate(
          tester,
          initialTime: const TimeOfDay(hour: 7, minute: 41),
          materialType: materialType,
        );

        final double minutesDisplayHeight = tester.getSize(find.text('41')).height;
        final double amHeight = tester.getSize(find.text(amString)).height;

        await tester.tap(find.text(okString)); // dismiss the dialog
        await tester.pumpAndSettle();

        // Verify that the time display is not affected by text scale.
        await mediaQueryBoilerplate(
          tester,
          textScaleFactor: 2,
          initialTime: const TimeOfDay(hour: 7, minute: 41),
          materialType: materialType,
        );

        final double amHeight2x = tester.getSize(find.text(amString)).height;
        expect(tester.getSize(find.text('41')).height, equals(minutesDisplayHeight));
1094
        expect(amHeight2x, math.min(38.0, amHeight * 2));
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

        await tester.tap(find.text(okString)); // dismiss the dialog
        await tester.pumpAndSettle();

        // Verify that text scale for AM/PM is at most 2x.
        await mediaQueryBoilerplate(
          tester,
          textScaleFactor: 3,
          initialTime: const TimeOfDay(hour: 7, minute: 41),
          materialType: materialType,
        );

        expect(tester.getSize(find.text('41')).height, equals(minutesDisplayHeight));
1108
        expect(tester.getSize(find.text(amString)).height, math.min(38.0, amHeight * 2));
1109 1110 1111
      });

      group('showTimePicker avoids overlapping display features', () {
1112
        testWidgetsWithLeakTracking('positioning with anchorPoint', (WidgetTester tester) async {
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
          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'));

          showTimePicker(
            context: context,
            initialTime: const TimeOfDay(hour: 7, minute: 0),
            anchorPoint: const Offset(1000, 0),
          );

          await tester.pumpAndSettle();
          // Should take the right side of the screen
          expect(tester.getTopLeft(find.byType(TimePickerDialog)), const Offset(410, 0));
          expect(tester.getBottomRight(find.byType(TimePickerDialog)), const Offset(800, 600));
        });

1148
        testWidgetsWithLeakTracking('positioning with Directionality', (WidgetTester tester) async {
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
          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'));

          // By default it should place the dialog on the right screen
          showTimePicker(
            context: context,
            initialTime: const TimeOfDay(hour: 7, minute: 0),
          );

          await tester.pumpAndSettle();
          expect(tester.getTopLeft(find.byType(TimePickerDialog)), const Offset(410, 0));
          expect(tester.getBottomRight(find.byType(TimePickerDialog)), const Offset(800, 600));
        });

1186
        testWidgetsWithLeakTracking('positioning with defaults', (WidgetTester tester) async {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
          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'));

          // By default it should place the dialog on the left screen
          showTimePicker(
            context: context,
            initialTime: const TimeOfDay(hour: 7, minute: 0),
          );

          await tester.pumpAndSettle();
          expect(tester.getTopLeft(find.byType(TimePickerDialog)), Offset.zero);
          expect(tester.getBottomRight(find.byType(TimePickerDialog)), const Offset(390, 600));
        });
      });

      group('Works for various view sizes', () {
        for (final Size size in const <Size>[Size(100, 100), Size(300, 300), Size(800, 600)]) {
1224
          testWidgetsWithLeakTracking('Draws dial without overflows at $size', (WidgetTester tester) async {
1225 1226 1227
            tester.view.physicalSize = size;
            addTearDown(tester.view.reset);

1228 1229 1230 1231 1232
            await mediaQueryBoilerplate(tester, entryMode: TimePickerEntryMode.input, materialType: materialType);
            await tester.pumpAndSettle();
            expect(tester.takeException(), isNot(throwsAssertionError));
          });

1233
          testWidgetsWithLeakTracking('Draws input without overflows at $size', (WidgetTester tester) async {
1234 1235 1236
            tester.view.physicalSize = size;
            addTearDown(tester.view.reset);

1237 1238 1239 1240 1241 1242 1243 1244 1245
            await mediaQueryBoilerplate(tester, materialType: materialType);
            await tester.pumpAndSettle();
            expect(tester.takeException(), isNot(throwsAssertionError));
          });
        }
      });
    });

    group('Time picker - A11y and Semantics (${materialType.name})', () {
1246
      testWidgetsWithLeakTracking('provides semantics information for AM/PM indicator', (WidgetTester tester) async {
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
        final SemanticsTester semantics = SemanticsTester(tester);
        await mediaQueryBoilerplate(tester, materialType: materialType);

        expect(
          semantics,
          includesNodeWith(
            label: amString,
            actions: <SemanticsAction>[SemanticsAction.tap],
            flags: <SemanticsFlag>[
              SemanticsFlag.isButton,
              SemanticsFlag.isChecked,
              SemanticsFlag.isInMutuallyExclusiveGroup,
              SemanticsFlag.hasCheckedState,
              SemanticsFlag.isFocusable,
            ],
          ),
        );
        expect(
          semantics,
          includesNodeWith(
            label: pmString,
            actions: <SemanticsAction>[SemanticsAction.tap],
            flags: <SemanticsFlag>[
              SemanticsFlag.isButton,
              SemanticsFlag.isInMutuallyExclusiveGroup,
              SemanticsFlag.hasCheckedState,
              SemanticsFlag.isFocusable,
            ],
          ),
        );

        semantics.dispose();
      });

1281
      testWidgetsWithLeakTracking('Material2 - provides semantics information for header and footer', (WidgetTester tester) async {
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        final SemanticsTester semantics = SemanticsTester(tester);
        await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, materialType: MaterialType.material2);

        expect(semantics, isNot(includesNodeWith(label: ':')));
        expect(
          semantics.nodesWith(value: 'Select minutes 00'),
          hasLength(1),
          reason: '00 appears once in the header',
        );
        expect(
          semantics.nodesWith(value: 'Select hours 07'),
          hasLength(1),
          reason: '07 appears once in the header',
        );
        expect(semantics, includesNodeWith(label: 'CANCEL'));
        expect(semantics, includesNodeWith(label: okString));

        // In 24-hour mode we don't have AM/PM control.
        expect(semantics, isNot(includesNodeWith(label: amString)));
        expect(semantics, isNot(includesNodeWith(label: pmString)));

        semantics.dispose();
      });

1306
      testWidgetsWithLeakTracking('Material3 - provides semantics information for header and footer', (WidgetTester tester) async {
1307
        final SemanticsTester semantics = SemanticsTester(tester);
1308
        await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, materialType: MaterialType.material3);
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

        expect(semantics, isNot(includesNodeWith(label: ':')));
        expect(
          semantics.nodesWith(value: 'Select minutes 00'),
          hasLength(1),
          reason: '00 appears once in the header',
        );
        expect(
          semantics.nodesWith(value: 'Select hours 07'),
          hasLength(1),
          reason: '07 appears once in the header',
        );
1321
        expect(semantics, includesNodeWith(label: 'Cancel'));
1322 1323 1324 1325 1326 1327 1328 1329 1330
        expect(semantics, includesNodeWith(label: okString));

        // In 24-hour mode we don't have AM/PM control.
        expect(semantics, isNot(includesNodeWith(label: amString)));
        expect(semantics, isNot(includesNodeWith(label: pmString)));

        semantics.dispose();
      });

1331
      testWidgetsWithLeakTracking('provides semantics information for text fields', (WidgetTester tester) async {
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        final SemanticsTester semantics = SemanticsTester(tester);
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          accessibleNavigation: true,
          materialType: materialType,
        );

        expect(
          semantics,
          includesNodeWith(
            label: 'Hour',
            value: '07',
            actions: <SemanticsAction>[SemanticsAction.tap],
            flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.isMultiline],
          ),
        );
        expect(
          semantics,
          includesNodeWith(
            label: 'Minute',
            value: '00',
            actions: <SemanticsAction>[SemanticsAction.tap],
            flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.isMultiline],
          ),
        );

        semantics.dispose();
      });

1363
      testWidgetsWithLeakTracking('can increment and decrement hours', (WidgetTester tester) async {
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
        final SemanticsTester semantics = SemanticsTester(tester);

        Future<void> actAndExpect({
          required String initialValue,
          required SemanticsAction action,
          required String finalValue,
        }) async {
          final SemanticsNode elevenHours = semantics
              .nodesWith(
                value: 'Select hours $initialValue',
                ancestor: tester.renderObject(_hourControl).debugSemantics,
              )
              .single;
          tester.binding.pipelineOwner.semanticsOwner!.performAction(elevenHours.id, action);
          await tester.pumpAndSettle();
          expect(
            find.descendant(of: _hourControl, matching: find.text(finalValue)),
            findsOneWidget,
          );
        }

        // 12-hour format
        await mediaQueryBoilerplate(
          tester,
          initialTime: const TimeOfDay(hour: 11, minute: 0),
          materialType: materialType,
        );
        await actAndExpect(
          initialValue: '11',
          action: SemanticsAction.increase,
          finalValue: '12',
        );
        await actAndExpect(
          initialValue: '12',
          action: SemanticsAction.increase,
          finalValue: '1',
        );

        // Ensure we preserve day period as we roll over.
        final dynamic pickerState = tester.state(_timePicker);
        // ignore: avoid_dynamic_calls
        expect(pickerState.selectedTime.value, const TimeOfDay(hour: 1, minute: 0));

        await actAndExpect(
          initialValue: '1',
          action: SemanticsAction.decrease,
          finalValue: '12',
        );
        await tester.pumpWidget(Container()); // clear old boilerplate

        // 24-hour format
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          initialTime: const TimeOfDay(hour: 23, minute: 0),
          materialType: materialType,
        );
        await actAndExpect(
          initialValue: '23',
          action: SemanticsAction.increase,
          finalValue: '00',
        );
        await actAndExpect(
          initialValue: '00',
          action: SemanticsAction.increase,
          finalValue: '01',
        );
        await actAndExpect(
          initialValue: '01',
          action: SemanticsAction.decrease,
          finalValue: '00',
        );
        await actAndExpect(
          initialValue: '00',
          action: SemanticsAction.decrease,
          finalValue: '23',
        );

        semantics.dispose();
      });

1445
      testWidgetsWithLeakTracking('can increment and decrement minutes', (WidgetTester tester) async {
1446 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 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
        final SemanticsTester semantics = SemanticsTester(tester);

        Future<void> actAndExpect({
          required String initialValue,
          required SemanticsAction action,
          required String finalValue,
        }) async {
          final SemanticsNode elevenHours = semantics
              .nodesWith(
                value: 'Select minutes $initialValue',
                ancestor: tester.renderObject(_minuteControl).debugSemantics,
              )
              .single;
          tester.binding.pipelineOwner.semanticsOwner!.performAction(elevenHours.id, action);
          await tester.pumpAndSettle();
          expect(
            find.descendant(of: _minuteControl, matching: find.text(finalValue)),
            findsOneWidget,
          );
        }

        await mediaQueryBoilerplate(
          tester,
          initialTime: const TimeOfDay(hour: 11, minute: 58),
          materialType: materialType,
        );
        await actAndExpect(
          initialValue: '58',
          action: SemanticsAction.increase,
          finalValue: '59',
        );
        await actAndExpect(
          initialValue: '59',
          action: SemanticsAction.increase,
          finalValue: '00',
        );

        // Ensure we preserve hour period as we roll over.
        final dynamic pickerState = tester.state(_timePicker);
        // ignore: avoid_dynamic_calls
        expect(pickerState.selectedTime.value, const TimeOfDay(hour: 11, minute: 0));

        await actAndExpect(
          initialValue: '00',
          action: SemanticsAction.decrease,
          finalValue: '59',
        );
        await actAndExpect(
          initialValue: '59',
          action: SemanticsAction.decrease,
          finalValue: '58',
        );

        semantics.dispose();
      });

1502
      testWidgetsWithLeakTracking('header touch regions are large enough', (WidgetTester tester) async {
1503
        // Ensure picker is displayed in portrait mode.
1504 1505 1506 1507
        tester.view.physicalSize = const Size(400, 800);
        tester.view.devicePixelRatio = 1;
        addTearDown(tester.view.reset);

1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
        await mediaQueryBoilerplate(tester, materialType: materialType);

        final Size dayPeriodControlSize = tester.getSize(
          find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodControl'),
        );
        expect(dayPeriodControlSize.width, greaterThanOrEqualTo(48));
        expect(dayPeriodControlSize.height, greaterThanOrEqualTo(80));

        final Size hourSize = tester.getSize(find.ancestor(
          of: find.text('7'),
          matching: find.byType(InkWell),
        ));
        expect(hourSize.width, greaterThanOrEqualTo(48));
        expect(hourSize.height, greaterThanOrEqualTo(48));

        final Size minuteSize = tester.getSize(find.ancestor(
          of: find.text('00'),
          matching: find.byType(InkWell),
        ));
        expect(minuteSize.width, greaterThanOrEqualTo(48));
        expect(minuteSize.height, greaterThanOrEqualTo(48));
      });
    });

    group('Time picker - Input (${materialType.name})', () {
1533
      testWidgetsWithLeakTracking('Initial entry mode is used', (WidgetTester tester) async {
1534 1535 1536 1537 1538 1539 1540 1541 1542
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          materialType: materialType,
        );
        expect(find.byType(TextField), findsNWidgets(2));
      });

1543
      testWidgetsWithLeakTracking('Initial time is the default', (WidgetTester tester) async {
1544 1545 1546 1547 1548 1549 1550 1551
        late TimeOfDay result;
        await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, entryMode: TimePickerEntryMode.input, materialType: materialType);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 7, minute: 0)));
      });

1552
      testWidgetsWithLeakTracking('Help text is used - Input', (WidgetTester tester) async {
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
        const String helpText = 'help';
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          helpText: helpText,
          materialType: materialType,
        );
        expect(find.text(helpText), findsOneWidget);
      });

1564
      testWidgetsWithLeakTracking('Help text is used in Material3 - Input', (WidgetTester tester) async {
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
        const String helpText = 'help';
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          helpText: helpText,
          materialType: materialType,
        );
        expect(find.text(helpText), findsOneWidget);
      });

1576
      testWidgetsWithLeakTracking('Hour label text is used - Input', (WidgetTester tester) async {
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
        const String hourLabelText = 'Custom hour label';
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          hourLabelText: hourLabelText,
          materialType: materialType,
        );
        expect(find.text(hourLabelText), findsOneWidget);
      });

1588
      testWidgetsWithLeakTracking('Minute label text is used - Input', (WidgetTester tester) async {
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
        const String minuteLabelText = 'Custom minute label';
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          minuteLabelText: minuteLabelText,
          materialType: materialType,
        );
        expect(find.text(minuteLabelText), findsOneWidget);
      });

1600
      testWidgetsWithLeakTracking('Invalid error text is used - Input', (WidgetTester tester) async {
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
        const String errorInvalidText = 'Custom validation error';
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          errorInvalidText: errorInvalidText,
          materialType: materialType,
        );
        // Input invalid time (hour) to force validation error
        await tester.enterText(find.byType(TextField).first, '88');
        final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(
          tester.element(find.byType(TextButton).first),
        );
        // Tap the ok button to trigger the validation error with custom translation
        await tester.tap(find.text(materialLocalizations.okButtonLabel));
        await tester.pumpAndSettle(const Duration(seconds: 1));
        expect(find.text(errorInvalidText), findsOneWidget);
      });

1620
      testWidgetsWithLeakTracking('Can switch from input to dial entry mode', (WidgetTester tester) async {
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          materialType: materialType,
        );
        await tester.tap(find.byIcon(Icons.access_time));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsNothing);
      });

1632
      testWidgetsWithLeakTracking('Can switch from dial to input entry mode', (WidgetTester tester) async {
1633 1634 1635 1636 1637 1638
        await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, materialType: materialType);
        await tester.tap(find.byIcon(Icons.keyboard_outlined));
        await tester.pumpAndSettle();
        expect(find.byType(TextField), findsWidgets);
      });

1639
      testWidgetsWithLeakTracking('Can not switch out of inputOnly mode', (WidgetTester tester) async {
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.inputOnly,
          materialType: materialType,
        );
        expect(find.byType(TextField), findsWidgets);
        expect(find.byIcon(Icons.access_time), findsNothing);
      });

1650
      testWidgetsWithLeakTracking('Can not switch out of dialOnly mode', (WidgetTester tester) async {
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.dialOnly,
          materialType: materialType,
        );
        expect(find.byType(TextField), findsNothing);
        expect(find.byIcon(Icons.keyboard_outlined), findsNothing);
      });

1661
      testWidgetsWithLeakTracking('Switching to dial entry mode triggers entry callback', (WidgetTester tester) async {
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
        bool triggeredCallback = false;

        await mediaQueryBoilerplate(
          tester,
          alwaysUse24HourFormat: true,
          entryMode: TimePickerEntryMode.input,
          onEntryModeChange: (TimePickerEntryMode mode) {
            if (mode == TimePickerEntryMode.dial) {
              triggeredCallback = true;
            }
          },
          materialType: materialType,
        );

        await tester.tap(find.byIcon(Icons.access_time));
        await tester.pumpAndSettle();
        expect(triggeredCallback, true);
      });

1681
      testWidgetsWithLeakTracking('Switching to input entry mode triggers entry callback', (WidgetTester tester) async {
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
        bool triggeredCallback = false;

        await mediaQueryBoilerplate(tester, alwaysUse24HourFormat: true, onEntryModeChange: (TimePickerEntryMode mode) {
          if (mode == TimePickerEntryMode.input) {
            triggeredCallback = true;
          }
        }, materialType: materialType);

        await tester.tap(find.byIcon(Icons.keyboard_outlined));
        await tester.pumpAndSettle();
        expect(triggeredCallback, true);
      });

1695
      testWidgetsWithLeakTracking('Can double tap hours (when selected) to enter input mode', (WidgetTester tester) async {
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
        await mediaQueryBoilerplate(tester, materialType: materialType);
        final Finder hourFinder = find.ancestor(
          of: find.text('7'),
          matching: find.byType(InkWell),
        );

        expect(find.byType(TextField), findsNothing);

        // Double tap the hour.
        await tester.tap(hourFinder);
        await tester.pump(const Duration(milliseconds: 100));
        await tester.tap(hourFinder);
        await tester.pumpAndSettle();

        expect(find.byType(TextField), findsWidgets);
      });

1713
      testWidgetsWithLeakTracking('Can not double tap hours (when not selected) to enter input mode', (WidgetTester tester) async {
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
        await mediaQueryBoilerplate(tester, materialType: materialType);
        final Finder hourFinder = find.ancestor(
          of: find.text('7'),
          matching: find.byType(InkWell),
        );
        final Finder minuteFinder = find.ancestor(
          of: find.text('00'),
          matching: find.byType(InkWell),
        );

        expect(find.byType(TextField), findsNothing);

        // Switch to minutes mode.
        await tester.tap(minuteFinder);
        await tester.pumpAndSettle();

        // Double tap the hour.
        await tester.tap(hourFinder);
        await tester.pump(const Duration(milliseconds: 100));
        await tester.tap(hourFinder);
        await tester.pumpAndSettle();

        expect(find.byType(TextField), findsNothing);
      });

1739
      testWidgetsWithLeakTracking('Can double tap minutes (when selected) to enter input mode', (WidgetTester tester) async {
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
        await mediaQueryBoilerplate(tester, materialType: materialType);
        final Finder minuteFinder = find.ancestor(
          of: find.text('00'),
          matching: find.byType(InkWell),
        );

        expect(find.byType(TextField), findsNothing);

        // Switch to minutes mode.
        await tester.tap(minuteFinder);
        await tester.pumpAndSettle();

        // Double tap the minutes.
        await tester.tap(minuteFinder);
        await tester.pump(const Duration(milliseconds: 100));
        await tester.tap(minuteFinder);
        await tester.pumpAndSettle();

        expect(find.byType(TextField), findsWidgets);
      });

1761
      testWidgetsWithLeakTracking('Can not double tap minutes (when not selected) to enter input mode', (WidgetTester tester) async {
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
        await mediaQueryBoilerplate(tester, materialType: materialType);
        final Finder minuteFinder = find.ancestor(
          of: find.text('00'),
          matching: find.byType(InkWell),
        );

        expect(find.byType(TextField), findsNothing);

        // Double tap the minutes.
        await tester.tap(minuteFinder);
        await tester.pump(const Duration(milliseconds: 100));
        await tester.tap(minuteFinder);
        await tester.pumpAndSettle();

        expect(find.byType(TextField), findsNothing);
      });

1779
      testWidgetsWithLeakTracking('Entered text returns time', (WidgetTester tester) async {
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        late TimeOfDay result;
        await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, entryMode: TimePickerEntryMode.input, materialType: materialType);
        await tester.enterText(find.byType(TextField).first, '9');
        await tester.enterText(find.byType(TextField).last, '12');
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 9, minute: 12)));
      });

1790
      testWidgetsWithLeakTracking('Toggle to dial mode keeps selected time', (WidgetTester tester) async {
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
        late TimeOfDay result;
        await startPicker(tester, (TimeOfDay? time) {
          result = time!;
        }, entryMode: TimePickerEntryMode.input, materialType: materialType);
        await tester.enterText(find.byType(TextField).first, '8');
        await tester.enterText(find.byType(TextField).last, '15');
        await tester.tap(find.byIcon(Icons.access_time));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 8, minute: 15)));
      });

1802
      testWidgetsWithLeakTracking('Invalid text prevents dismissing', (WidgetTester tester) async {
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
        TimeOfDay? result;
        await startPicker(tester, (TimeOfDay? time) {
          result = time;
        }, entryMode: TimePickerEntryMode.input, materialType: materialType);

        // Invalid hour.
        await tester.enterText(find.byType(TextField).first, '88');
        await tester.enterText(find.byType(TextField).last, '15');
        await finishPicker(tester);
        expect(result, null);

        // Invalid minute.
        await tester.enterText(find.byType(TextField).first, '8');
        await tester.enterText(find.byType(TextField).last, '95');
        await finishPicker(tester);
        expect(result, null);

        await tester.enterText(find.byType(TextField).first, '8');
        await tester.enterText(find.byType(TextField).last, '15');
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 8, minute: 15)));
      });

      // Fixes regression that was reverted in https://github.com/flutter/flutter/pull/64094#pullrequestreview-469836378.
1827
      testWidgetsWithLeakTracking('Ensure hour/minute fields are top-aligned with the separator', (WidgetTester tester) async {
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
        await startPicker(tester, (TimeOfDay? time) {},
            entryMode: TimePickerEntryMode.input, materialType: materialType);
        final double hourFieldTop =
            tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_HourTextField')).dy;
        final double minuteFieldTop =
            tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_MinuteTextField')).dy;
        final double separatorTop =
            tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_StringFragment')).dy;
        expect(hourFieldTop, separatorTop);
        expect(minuteFieldTop, separatorTop);
      });

1840
      testWidgetsWithLeakTracking('Can switch between hour/minute fields using keyboard input action', (WidgetTester tester) async {
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
        await startPicker(tester, (TimeOfDay? time) {},
            entryMode: TimePickerEntryMode.input, materialType: materialType);

        final Finder hourFinder = find.byType(TextField).first;
        final TextField hourField = tester.widget(hourFinder);
        await tester.tap(hourFinder);
        expect(hourField.focusNode!.hasFocus, isTrue);

        await tester.enterText(find.byType(TextField).first, '08');
        final Finder minuteFinder = find.byType(TextField).last;
        final TextField minuteField = tester.widget(minuteFinder);
        expect(hourField.focusNode!.hasFocus, isFalse);
        expect(minuteField.focusNode!.hasFocus, isTrue);

        expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done'));
        await tester.testTextInput.receiveAction(TextInputAction.done);
        expect(hourField.focusNode!.hasFocus, isFalse);
        expect(minuteField.focusNode!.hasFocus, isFalse);
      });
    });

    group('Time picker - Restoration (${materialType.name})', () {
1863
      testWidgetsWithLeakTracking('Time Picker state restoration test - dial mode', (WidgetTester tester) async {
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
        TimeOfDay? result;
        final Offset center = (await startPicker(
          tester,
          (TimeOfDay? time) {
            result = time;
          },
          restorationId: 'restorable_time_picker',
          materialType: materialType,
        ))!;
        final Offset hour6 = Offset(center.dx, center.dy + 50); // 6:00
        final Offset min45 = Offset(center.dx - 50, center.dy); // 45 mins (or 9:00 hours)

        await tester.tapAt(hour6);
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();
        await tester.tapAt(min45);
        await tester.pump(const Duration(milliseconds: 50));
        final TestRestorationData restorationData = await tester.getRestorationData();
        await tester.restartAndRestore();
        // Setting to PM adds 12 hours (18:45)
        await tester.tap(find.text(pmString));
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 18, minute: 45)));

        // Test restoring from before PM was selected (6:45)
        await tester.restoreFrom(restorationData);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 45)));
      });

1896
      testWidgetsWithLeakTracking('Time Picker state restoration test - input mode', (WidgetTester tester) async {
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
        TimeOfDay? result;
        await startPicker(
          tester,
          (TimeOfDay? time) {
            result = time;
          },
          entryMode: TimePickerEntryMode.input,
          restorationId: 'restorable_time_picker',
          materialType: materialType,
        );
        await tester.enterText(find.byType(TextField).first, '9');
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();

        await tester.enterText(find.byType(TextField).last, '12');
        await tester.pump(const Duration(milliseconds: 50));
        final TestRestorationData restorationData = await tester.getRestorationData();
        await tester.restartAndRestore();

        // Setting to PM adds 12 hours (21:12)
        await tester.tap(find.text(pmString));
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();

        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 21, minute: 12)));

        // Restoring from before PM was set (9:12)
        await tester.restoreFrom(restorationData);
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 9, minute: 12)));
      });

1930
      testWidgetsWithLeakTracking('Time Picker state restoration test - switching modes', (WidgetTester tester) async {
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 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 1985
        TimeOfDay? result;
        final Offset center = (await startPicker(
          tester,
          (TimeOfDay? time) {
            result = time;
          },
          restorationId: 'restorable_time_picker',
          materialType: materialType,
        ))!;

        final TestRestorationData restorationData = await tester.getRestorationData();
        // Switch to input mode from dial mode.
        await tester.tap(find.byIcon(Icons.keyboard_outlined));
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();

        // Select time using input mode controls.
        await tester.enterText(find.byType(TextField).first, '9');
        await tester.enterText(find.byType(TextField).last, '12');
        await tester.pump(const Duration(milliseconds: 50));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 9, minute: 12)));

        // Restoring from dial mode.
        await tester.restoreFrom(restorationData);
        final Offset hour6 = Offset(center.dx, center.dy + 50); // 6:00
        final Offset min45 = Offset(center.dx - 50, center.dy); // 45 mins (or 9:00 hours)

        await tester.tapAt(hour6);
        await tester.pump(const Duration(milliseconds: 50));
        await tester.restartAndRestore();
        await tester.tapAt(min45);
        await tester.pump(const Duration(milliseconds: 50));
        await finishPicker(tester);
        expect(result, equals(const TimeOfDay(hour: 6, minute: 45)));
      });
    });
  }
}

final Finder findDialPaint = find.descendant(
  of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_Dial'),
  matching: find.byWidgetPredicate((Widget w) => w is CustomPaint),
);

class PickerObserver extends NavigatorObserver {
  int pickerCount = 0;

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (route is DialogRoute) {
      pickerCount++;
    }
    super.didPush(route, previousRoute);
  }
1986 1987 1988 1989 1990 1991 1992 1993

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (route is DialogRoute) {
      pickerCount--;
    }
    super.didPop(route, previousRoute);
  }
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
}

Future<void> mediaQueryBoilerplate(
  WidgetTester tester, {
  bool alwaysUse24HourFormat = false,
  TimeOfDay initialTime = const TimeOfDay(hour: 7, minute: 0),
  double textScaleFactor = 1,
  TimePickerEntryMode entryMode = TimePickerEntryMode.dial,
  String? helpText,
  String? hourLabelText,
  String? minuteLabelText,
  String? errorInvalidText,
  bool accessibleNavigation = false,
  EntryModeChangeCallback? onEntryModeChange,
  bool tapButton = true,
  required MaterialType materialType,
  Orientation? orientation,
}) async {
  await tester.pumpWidget(
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 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
    Theme(
      data: ThemeData(useMaterial3: materialType == MaterialType.material3),
      child: Localizations(
        locale: const Locale('en', 'US'),
        delegates: const <LocalizationsDelegate<dynamic>>[
          DefaultMaterialLocalizations.delegate,
          DefaultWidgetsLocalizations.delegate,
        ],
        child: MediaQuery(
          data: MediaQueryData(
            alwaysUse24HourFormat: alwaysUse24HourFormat,
            textScaleFactor: textScaleFactor,
            accessibleNavigation: accessibleNavigation,
            size: tester.view.physicalSize / tester.view.devicePixelRatio,
          ),
          child: Material(
            child: Center(
              child: Directionality(
                textDirection: TextDirection.ltr,
                child: Navigator(
                  onGenerateRoute: (RouteSettings settings) {
                    return MaterialPageRoute<void>(builder: (BuildContext context) {
                      return TextButton(
                        onPressed: () {
                          showTimePicker(
                            context: context,
                            initialTime: initialTime,
                            initialEntryMode: entryMode,
                            helpText: helpText,
                            hourLabelText: hourLabelText,
                            minuteLabelText: minuteLabelText,
                            errorInvalidText: errorInvalidText,
                            onEntryModeChanged: onEntryModeChange,
                            orientation: orientation,
                          );
                        },
                        child: const Text('X'),
                      );
                    });
                  },
2053 2054 2055 2056 2057
                ),
              ),
            ),
          ),
        ),
2058 2059
      ),
    ),
2060 2061 2062 2063 2064 2065 2066
  );
  if (tapButton) {
    await tester.tap(find.text('X'));
  }
  await tester.pumpAndSettle();
}

2067 2068
final Finder _hourControl = find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_HourControl');
final Finder _minuteControl = find.byWidgetPredicate((Widget widget) => '${widget.runtimeType}' == '_MinuteControl');
2069
final Finder _timePicker = find.byWidgetPredicate((Widget widget) => '${widget.runtimeType}' == '_TimePicker');
2070

2071
class _TimePickerLauncher extends StatefulWidget {
2072
  const _TimePickerLauncher({
2073
    required this.onChanged,
2074
    this.entryMode = TimePickerEntryMode.dial,
2075
    this.restorationId,
2076
  });
2077

2078
  final ValueChanged<TimeOfDay?> onChanged;
2079
  final TimePickerEntryMode entryMode;
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
  final String? restorationId;

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

class _TimePickerLauncherState extends State<_TimePickerLauncher> with RestorationMixin {
  @override
  String? get restorationId => widget.restorationId;

  late final RestorableRouteFuture<TimeOfDay?> _restorableTimePickerRouteFuture = RestorableRouteFuture<TimeOfDay?>(
    onComplete: _selectTime,
    onPresent: (NavigatorState navigator, Object? arguments) {
      return navigator.restorablePush(
        _timePickerRoute,
2095 2096
        arguments: <String, String>{
          'entry_mode': widget.entryMode.name,
2097 2098 2099 2100 2101
        },
      );
    },
  );

2102 2103 2104 2105 2106 2107
  @override
  void dispose() {
    _restorableTimePickerRouteFuture.dispose();
    super.dispose();
  }

2108
  @pragma('vm:entry-point')
2109 2110 2111 2112 2113
  static Route<TimeOfDay> _timePickerRoute(
    BuildContext context,
    Object? arguments,
  ) {
    final Map<dynamic, dynamic> args = arguments! as Map<dynamic, dynamic>;
2114 2115 2116
    final TimePickerEntryMode entryMode = TimePickerEntryMode.values.firstWhere(
      (TimePickerEntryMode element) => element.name == args['entry_mode'],
    );
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
    return DialogRoute<TimeOfDay>(
      context: context,
      builder: (BuildContext context) {
        return TimePickerDialog(
          restorationId: 'time_picker_dialog',
          initialTime: const TimeOfDay(hour: 7, minute: 0),
          initialEntryMode: entryMode,
        );
      },
    );
  }

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(_restorableTimePickerRouteFuture, 'time_picker_route_future');
  }

  void _selectTime(TimeOfDay? newSelectedTime) {
    widget.onChanged(newSelectedTime);
  }
2137 2138 2139

  @override
  Widget build(BuildContext context) {
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
    return Material(
      child: Center(
        child: Builder(
          builder: (BuildContext context) {
            return ElevatedButton(
              child: const Text('X'),
              onPressed: () async {
                if (widget.restorationId == null) {
                  widget.onChanged(await showTimePicker(
                    context: context,
                    initialTime: const TimeOfDay(hour: 7, minute: 0),
                    initialEntryMode: widget.entryMode,
                  ));
                } else {
                  _restorableTimePickerRouteFuture.present();
                }
              },
            );
          },
2159 2160
        ),
      ),
2161
    );
2162 2163
  }
}
Hans Muller's avatar
Hans Muller committed
2164

2165 2166 2167 2168 2169 2170 2171 2172 2173
// The version of material design layout, etc. to test. Corresponds to
// useMaterial3 true/false in the ThemeData, but used an enum here so that it
// wasn't just a boolean, for easier identification of the name of the mode in
// tests.
enum MaterialType {
  material2,
  material3,
}

2174
Future<Offset?> startPicker(
2175 2176 2177 2178 2179 2180
  WidgetTester tester,
  ValueChanged<TimeOfDay?> onChanged, {
  TimePickerEntryMode entryMode = TimePickerEntryMode.dial,
  String? restorationId,
  required MaterialType materialType,
}) async {
2181
  await tester.pumpWidget(MaterialApp(
2182
    theme: ThemeData(useMaterial3: materialType == MaterialType.material3),
2183 2184 2185 2186 2187 2188 2189 2190
    restorationScopeId: 'app',
    locale: const Locale('en', 'US'),
    home: _TimePickerLauncher(
      onChanged: onChanged,
      entryMode: entryMode,
      restorationId: restorationId,
    ),
  ));
2191
  await tester.tap(find.text('X'));
2192
  await tester.pumpAndSettle(const Duration(seconds: 1));
2193 2194 2195
  return entryMode == TimePickerEntryMode.dial
      ? tester.getCenter(find.byKey(const ValueKey<String>('time-picker-dial')))
      : null;
2196
}
Hans Muller's avatar
Hans Muller committed
2197

2198
Future<void> finishPicker(WidgetTester tester) async {
2199 2200 2201
  final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(
    tester.element(find.byType(ElevatedButton)),
  );
Yegor's avatar
Yegor committed
2202
  await tester.tap(find.text(materialLocalizations.okButtonLabel));
2203
  await tester.pumpAndSettle(const Duration(seconds: 1));
2204
}