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

5
import 'dart:async';
6
import 'dart:math' as math;
7
import 'dart:ui' as ui;
8

9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/services.dart';
11 12
import 'package:flutter/widgets.dart';

13
import 'color_scheme.dart';
14
import 'colors.dart';
15 16
import 'constants.dart';
import 'curves.dart';
17
import 'debug.dart';
18
import 'dialog.dart';
19
import 'feedback.dart';
20 21
import 'icon_button.dart';
import 'icons.dart';
22
import 'ink_well.dart';
23 24
import 'input_border.dart';
import 'input_decorator.dart';
25
import 'material.dart';
26
import 'material_localizations.dart';
27
import 'material_state.dart';
28
import 'text_button.dart';
29
import 'text_form_field.dart';
30
import 'text_theme.dart';
31
import 'theme.dart';
32
import 'theme_data.dart';
33
import 'time.dart';
34
import 'time_picker_theme.dart';
35

36
// Examples can assume:
37
// late BuildContext context;
38

39
const Duration _kDialogSizeAnimationDuration = Duration(milliseconds: 200);
40
const Duration _kDialAnimateDuration = Duration(milliseconds: 200);
41
const double _kTwoPi = 2 * math.pi;
42
const Duration _kVibrateCommitDelay = Duration(milliseconds: 100);
Adam Barth's avatar
Adam Barth committed
43

44 45
enum _TimePickerMode { hour, minute }

46 47
const double _kTimePickerHeaderLandscapeWidth = 264.0;
const double _kTimePickerHeaderControlHeight = 80.0;
48

49
const double _kTimePickerWidthPortrait = 328.0;
50
const double _kTimePickerWidthLandscape = 528.0;
51

52
const double _kTimePickerHeightInput = 226.0;
53 54 55 56 57
const double _kTimePickerHeightPortrait = 496.0;
const double _kTimePickerHeightLandscape = 316.0;

const double _kTimePickerHeightPortraitCollapsed = 484.0;
const double _kTimePickerHeightLandscapeCollapsed = 304.0;
58

59 60
const BorderRadius _kDefaultBorderRadius = BorderRadius.all(Radius.circular(4.0));
const ShapeBorder _kDefaultShape = RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius);
Yegor's avatar
Yegor committed
61

62 63 64 65 66 67 68 69 70 71 72 73
/// Interactive input mode of the time picker dialog.
///
/// In [TimePickerEntryMode.dial] mode, a clock dial is displayed and
/// the user taps or drags the time they wish to select. In
/// TimePickerEntryMode.input] mode, [TextField]s are displayed and the user
/// types in the time they wish to select.
enum TimePickerEntryMode {
  /// Tapping/dragging on a clock dial.
  dial,

  /// Text input.
  input,
Yegor's avatar
Yegor committed
74 75 76 77 78 79
}

/// Provides properties for rendering time picker header fragments.
@immutable
class _TimePickerFragmentContext {
  const _TimePickerFragmentContext({
80 81 82 83 84 85 86
    required this.selectedTime,
    required this.mode,
    required this.onTimeChange,
    required this.onModeChange,
    required this.onHourDoubleTapped,
    required this.onMinuteDoubleTapped,
    required this.use24HourDials,
87
  }) : assert(selectedTime != null),
Yegor's avatar
Yegor committed
88 89
       assert(mode != null),
       assert(onTimeChange != null),
90
       assert(onModeChange != null),
91
       assert(use24HourDials != null);
Yegor's avatar
Yegor committed
92 93 94 95 96

  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
  final ValueChanged<TimeOfDay> onTimeChange;
  final ValueChanged<_TimePickerMode> onModeChange;
97 98
  final GestureTapCallback onHourDoubleTapped;
  final GestureTapCallback onMinuteDoubleTapped;
99
  final bool use24HourDials;
Yegor's avatar
Yegor committed
100 101
}

102 103
class _TimePickerHeader extends StatelessWidget {
  const _TimePickerHeader({
104 105 106 107 108 109 110 111 112
    required this.selectedTime,
    required this.mode,
    required this.orientation,
    required this.onModeChanged,
    required this.onChanged,
    required this.onHourDoubleTapped,
    required this.onMinuteDoubleTapped,
    required this.use24HourDials,
    required this.helpText,
113 114 115 116
  }) : assert(selectedTime != null),
       assert(mode != null),
       assert(orientation != null),
       assert(use24HourDials != null);
Yegor's avatar
Yegor committed
117

118 119
  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
120
  final Orientation orientation;
121 122
  final ValueChanged<_TimePickerMode> onModeChanged;
  final ValueChanged<TimeOfDay> onChanged;
123 124
  final GestureTapCallback onHourDoubleTapped;
  final GestureTapCallback onMinuteDoubleTapped;
125
  final bool use24HourDials;
126
  final String? helpText;
Yegor's avatar
Yegor committed
127

128 129 130
  void _handleChangeMode(_TimePickerMode value) {
    if (value != mode)
      onModeChanged(value);
Yegor's avatar
Yegor committed
131 132 133 134
  }

  @override
  Widget build(BuildContext context) {
135
    assert(debugCheckHasMediaQuery(context));
136
    final ThemeData themeData = Theme.of(context);
137
    final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(
138
      alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat,
Yegor's avatar
Yegor committed
139
    );
140 141 142 143 144 145

    final _TimePickerFragmentContext fragmentContext = _TimePickerFragmentContext(
      selectedTime: selectedTime,
      mode: mode,
      onTimeChange: onChanged,
      onModeChange: _handleChangeMode,
146 147
      onHourDoubleTapped: onHourDoubleTapped,
      onMinuteDoubleTapped: onMinuteDoubleTapped,
148
      use24HourDials: use24HourDials,
Yegor's avatar
Yegor committed
149
    );
150

151
    final EdgeInsets padding;
152
    double? width;
153
    final Widget controls;
154

155 156 157 158 159 160 161
    switch (orientation) {
      case Orientation.portrait:
        // Keep width null because in portrait we don't cap the width.
        padding = const EdgeInsets.symmetric(horizontal: 24.0);
        controls = Column(
          children: <Widget>[
            const SizedBox(height: 16.0),
162
            SizedBox(
163 164 165 166 167 168 169 170 171 172 173
              height: kMinInteractiveDimension * 2,
              child: Row(
                children: <Widget>[
                  if (!use24HourDials && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                    _DayPeriodControl(
                      selectedTime: selectedTime,
                      orientation: orientation,
                      onChanged: onChanged,
                    ),
                    const SizedBox(width: 12.0),
                  ],
174 175 176 177 178 179 180 181 182 183 184
                  Expanded(
                    child: Row(
                      // Hour/minutes should not change positions in RTL locales.
                      textDirection: TextDirection.ltr,
                      children: <Widget>[
                        Expanded(child: _HourControl(fragmentContext: fragmentContext)),
                        _StringFragment(timeOfDayFormat: timeOfDayFormat),
                        Expanded(child: _MinuteControl(fragmentContext: fragmentContext)),
                      ],
                    ),
                  ),
185 186 187 188 189 190 191
                  if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                    const SizedBox(width: 12.0),
                    _DayPeriodControl(
                      selectedTime: selectedTime,
                      orientation: orientation,
                      onChanged: onChanged,
                    ),
192
                  ],
193
                ],
194 195
              ),
            ),
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
          ],
        );
        break;
      case Orientation.landscape:
        width = _kTimePickerHeaderLandscapeWidth;
        padding = const EdgeInsets.symmetric(horizontal: 24.0);
        controls = Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              if (!use24HourDials && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm)
                _DayPeriodControl(
                  selectedTime: selectedTime,
                  orientation: orientation,
                  onChanged: onChanged,
                ),
212
              SizedBox(
213 214
                height: kMinInteractiveDimension * 2,
                child: Row(
215 216
                  // Hour/minutes should not change positions in RTL locales.
                  textDirection: TextDirection.ltr,
217 218 219 220 221 222 223 224 225 226 227 228 229 230
                  children: <Widget>[
                    Expanded(child: _HourControl(fragmentContext: fragmentContext)),
                    _StringFragment(timeOfDayFormat: timeOfDayFormat),
                    Expanded(child: _MinuteControl(fragmentContext: fragmentContext)),
                  ],
                ),
              ),
              if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm)
                _DayPeriodControl(
                  selectedTime: selectedTime,
                  orientation: orientation,
                  onChanged: onChanged,
                ),
            ],
231
          ),
232 233 234 235 236 237 238 239 240 241 242 243
        );
        break;
    }

    return Container(
      width: width,
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const SizedBox(height: 16.0),
          Text(
244
            helpText ?? MaterialLocalizations.of(context).timePickerDialHelpText,
245 246 247 248
            style: TimePickerTheme.of(context).helpTextStyle ?? themeData.textTheme.overline,
          ),
          controls,
        ],
249 250
      ),
    );
251 252 253 254 255
  }
}

class _HourMinuteControl extends StatelessWidget {
  const _HourMinuteControl({
256 257 258 259
    required this.text,
    required this.onTap,
    required this.onDoubleTap,
    required this.isSelected,
260 261 262 263 264 265
  }) : assert(text != null),
       assert(onTap != null),
       assert(isSelected != null);

  final String text;
  final GestureTapCallback onTap;
266
  final GestureTapCallback onDoubleTap;
267
  final bool isSelected;
268

269 270
  @override
  Widget build(BuildContext context) {
271
    final ThemeData themeData = Theme.of(context);
272 273 274 275 276 277 278 279 280 281 282 283 284 285
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
    final bool isDark = themeData.colorScheme.brightness == Brightness.dark;
    final Color textColor = timePickerTheme.hourMinuteTextColor
        ?? MaterialStateColor.resolveWith((Set<MaterialState> states) {
          return states.contains(MaterialState.selected)
              ? themeData.colorScheme.primary
              : themeData.colorScheme.onSurface;
        });
    final Color backgroundColor = timePickerTheme.hourMinuteColor
        ?? MaterialStateColor.resolveWith((Set<MaterialState> states) {
          return states.contains(MaterialState.selected)
              ? themeData.colorScheme.primary.withOpacity(isDark ? 0.24 : 0.12)
              : themeData.colorScheme.onSurface.withOpacity(0.12);
        });
286
    final TextStyle style = timePickerTheme.hourMinuteTextStyle ?? themeData.textTheme.headline2!;
287 288 289
    final ShapeBorder shape = timePickerTheme.hourMinuteShape ?? _kDefaultShape;

    final Set<MaterialState> states = isSelected ? <MaterialState>{MaterialState.selected} : <MaterialState>{};
290
    return SizedBox(
291
      height: _kTimePickerHeaderControlHeight,
292
      child: Material(
293 294 295
        color: MaterialStateProperty.resolveAs(backgroundColor, states),
        clipBehavior: Clip.antiAlias,
        shape: shape,
296
        child: InkWell(
297
          onTap: onTap,
298
          onDoubleTap: isSelected ? onDoubleTap : null,
299 300 301 302 303
          child: Center(
            child: Text(
              text,
              style: style.copyWith(color: MaterialStateProperty.resolveAs(textColor, states)),
              textScaleFactor: 1.0,
304
            ),
305 306
          ),
        ),
307
      ),
Yegor's avatar
Yegor committed
308 309 310 311 312 313 314 315
    );
  }
}
/// Displays the hour fragment.
///
/// When tapped changes time picker dial mode to [_TimePickerMode.hour].
class _HourControl extends StatelessWidget {
  const _HourControl({
316
    required this.fragmentContext,
Yegor's avatar
Yegor committed
317 318 319 320 321 322
  });

  final _TimePickerFragmentContext fragmentContext;

  @override
  Widget build(BuildContext context) {
323
    assert(debugCheckHasMediaQuery(context));
324
    final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat;
325
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
326 327
    final String formattedHour = localizations.formatHour(
      fragmentContext.selectedTime,
328 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
      alwaysUse24HourFormat: alwaysUse24HourFormat,
    );

    TimeOfDay hoursFromSelected(int hoursToAdd) {
      if (fragmentContext.use24HourDials) {
        final int selectedHour = fragmentContext.selectedTime.hour;
        return fragmentContext.selectedTime.replacing(
          hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay,
        );
      } else {
        // Cycle 1 through 12 without changing day period.
        final int periodOffset = fragmentContext.selectedTime.periodOffset;
        final int hours = fragmentContext.selectedTime.hourOfPeriod;
        return fragmentContext.selectedTime.replacing(
          hour: periodOffset + (hours + hoursToAdd) % TimeOfDay.hoursPerPeriod,
        );
      }
    }

    final TimeOfDay nextHour = hoursFromSelected(1);
    final String formattedNextHour = localizations.formatHour(
      nextHour,
      alwaysUse24HourFormat: alwaysUse24HourFormat,
    );
    final TimeOfDay previousHour = hoursFromSelected(-1);
    final String formattedPreviousHour = localizations.formatHour(
      previousHour,
      alwaysUse24HourFormat: alwaysUse24HourFormat,
356
    );
Yegor's avatar
Yegor committed
357

358
    return Semantics(
359
      value: '${localizations.timePickerHourModeAnnouncement} $formattedHour',
360 361 362 363 364 365 366 367 368
      excludeSemantics: true,
      increasedValue: formattedNextHour,
      onIncrease: () {
        fragmentContext.onTimeChange(nextHour);
      },
      decreasedValue: formattedPreviousHour,
      onDecrease: () {
        fragmentContext.onTimeChange(previousHour);
      },
369 370 371
      child: _HourMinuteControl(
        isSelected: fragmentContext.mode == _TimePickerMode.hour,
        text: formattedHour,
372
        onTap: Feedback.wrapForTap(() => fragmentContext.onModeChange(_TimePickerMode.hour), context)!,
373
        onDoubleTap: fragmentContext.onHourDoubleTapped,
374
      ),
Yegor's avatar
Yegor committed
375 376 377 378 379 380 381
    );
  }
}

/// A passive fragment showing a string value.
class _StringFragment extends StatelessWidget {
  const _StringFragment({
382
    required this.timeOfDayFormat,
Yegor's avatar
Yegor committed
383 384
  });

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  final TimeOfDayFormat timeOfDayFormat;

  String _stringFragmentValue(TimeOfDayFormat timeOfDayFormat) {
    switch (timeOfDayFormat) {
      case TimeOfDayFormat.h_colon_mm_space_a:
      case TimeOfDayFormat.a_space_h_colon_mm:
      case TimeOfDayFormat.H_colon_mm:
      case TimeOfDayFormat.HH_colon_mm:
        return ':';
      case TimeOfDayFormat.HH_dot_mm:
        return '.';
      case TimeOfDayFormat.frenchCanadian:
        return 'h';
    }
  }
Yegor's avatar
Yegor committed
400 401 402

  @override
  Widget build(BuildContext context) {
403
    final ThemeData theme = Theme.of(context);
404
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
405
    final TextStyle hourMinuteStyle = timePickerTheme.hourMinuteTextStyle ?? theme.textTheme.headline2!;
406 407
    final Color textColor = timePickerTheme.hourMinuteTextColor ?? theme.colorScheme.onSurface;

408
    return ExcludeSemantics(
409 410 411 412 413 414 415 416 417 418
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 6.0),
        child: Center(
          child: Text(
            _stringFragmentValue(timeOfDayFormat),
            style: hourMinuteStyle.apply(color: MaterialStateProperty.resolveAs(textColor, <MaterialState>{})),
            textScaleFactor: 1.0,
          ),
        ),
      ),
419
    );
Yegor's avatar
Yegor committed
420 421 422 423 424 425 426 427
  }
}

/// Displays the minute fragment.
///
/// When tapped changes time picker dial mode to [_TimePickerMode.minute].
class _MinuteControl extends StatelessWidget {
  const _MinuteControl({
428
    required this.fragmentContext,
Yegor's avatar
Yegor committed
429 430 431 432 433 434
  });

  final _TimePickerFragmentContext fragmentContext;

  @override
  Widget build(BuildContext context) {
435
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
436 437 438 439 440 441 442 443 444
    final String formattedMinute = localizations.formatMinute(fragmentContext.selectedTime);
    final TimeOfDay nextMinute = fragmentContext.selectedTime.replacing(
      minute: (fragmentContext.selectedTime.minute + 1) % TimeOfDay.minutesPerHour,
    );
    final String formattedNextMinute = localizations.formatMinute(nextMinute);
    final TimeOfDay previousMinute = fragmentContext.selectedTime.replacing(
      minute: (fragmentContext.selectedTime.minute - 1) % TimeOfDay.minutesPerHour,
    );
    final String formattedPreviousMinute = localizations.formatMinute(previousMinute);
Yegor's avatar
Yegor committed
445

446 447
    return Semantics(
      excludeSemantics: true,
448
      value: '${localizations.timePickerMinuteModeAnnouncement} $formattedMinute',
449 450 451 452 453 454 455 456
      increasedValue: formattedNextMinute,
      onIncrease: () {
        fragmentContext.onTimeChange(nextMinute);
      },
      decreasedValue: formattedPreviousMinute,
      onDecrease: () {
        fragmentContext.onTimeChange(previousMinute);
      },
457 458 459
      child: _HourMinuteControl(
        isSelected: fragmentContext.mode == _TimePickerMode.minute,
        text: formattedMinute,
460
        onTap: Feedback.wrapForTap(() => fragmentContext.onModeChange(_TimePickerMode.minute), context)!,
461
        onDoubleTap: fragmentContext.onMinuteDoubleTapped,
462
      ),
Yegor's avatar
Yegor committed
463 464 465 466 467
    );
  }
}


468 469 470 471
/// Displays the am/pm fragment and provides controls for switching between am
/// and pm.
class _DayPeriodControl extends StatelessWidget {
  const _DayPeriodControl({
472 473 474
    required this.selectedTime,
    required this.onChanged,
    required this.orientation,
475
  });
Yegor's avatar
Yegor committed
476

477 478 479
  final TimeOfDay selectedTime;
  final Orientation orientation;
  final ValueChanged<TimeOfDay> onChanged;
Yegor's avatar
Yegor committed
480

481 482 483 484
  void _togglePeriod() {
    final int newHour = (selectedTime.hour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay;
    final TimeOfDay newTime = selectedTime.replacing(hour: newHour);
    onChanged(newTime);
Yegor's avatar
Yegor committed
485 486
  }

487 488 489 490
  void _setAm(BuildContext context) {
    if (selectedTime.period == DayPeriod.am) {
      return;
    }
491
    switch (Theme.of(context).platform) {
492 493 494 495
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
496
        _announceToAccessibility(context, MaterialLocalizations.of(context).anteMeridiemAbbreviation);
Yegor's avatar
Yegor committed
497
        break;
498 499
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
Yegor's avatar
Yegor committed
500 501
        break;
    }
502 503 504 505 506 507
    _togglePeriod();
  }

  void _setPm(BuildContext context) {
    if (selectedTime.period == DayPeriod.pm) {
      return;
508
    }
509
    switch (Theme.of(context).platform) {
510 511 512 513
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
514
        _announceToAccessibility(context, MaterialLocalizations.of(context).postMeridiemAbbreviation);
515 516 517 518 519 520
        break;
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        break;
    }
    _togglePeriod();
Yegor's avatar
Yegor committed
521 522
  }

523 524
  @override
  Widget build(BuildContext context) {
525
    final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(context);
526
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
    final bool isDark = colorScheme.brightness == Brightness.dark;
    final Color textColor = timePickerTheme.dayPeriodTextColor
        ?? MaterialStateColor.resolveWith((Set<MaterialState> states) {
          return states.contains(MaterialState.selected)
              ? colorScheme.primary
              : colorScheme.onSurface.withOpacity(0.60);
        });
    final Color backgroundColor = timePickerTheme.dayPeriodColor
        ?? MaterialStateColor.resolveWith((Set<MaterialState> states) {
          // The unselected day period should match the overall picker dialog
          // color. Making it transparent enables that without being redundant
          // and allows the optional elevation overlay for dark mode to be
          // visible.
          return states.contains(MaterialState.selected)
              ? colorScheme.primary.withOpacity(isDark ? 0.24 : 0.12)
              : Colors.transparent;
        });
    final bool amSelected = selectedTime.period == DayPeriod.am;
    final Set<MaterialState> amStates = amSelected ? <MaterialState>{MaterialState.selected} : <MaterialState>{};
    final bool pmSelected = !amSelected;
    final Set<MaterialState> pmStates = pmSelected ? <MaterialState>{MaterialState.selected} : <MaterialState>{};
549
    final TextStyle textStyle = timePickerTheme.dayPeriodTextStyle ?? Theme.of(context).textTheme.subtitle1!;
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    final TextStyle amStyle = textStyle.copyWith(
      color: MaterialStateProperty.resolveAs(textColor, amStates),
    );
    final TextStyle pmStyle = textStyle.copyWith(
      color: MaterialStateProperty.resolveAs(textColor, pmStates),
    );
    OutlinedBorder shape = timePickerTheme.dayPeriodShape ??
        const RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius);
    final BorderSide borderSide = timePickerTheme.dayPeriodBorderSide ?? BorderSide(
      color: Color.alphaBlend(colorScheme.onBackground.withOpacity(0.38), colorScheme.surface),
    );
    // Apply the custom borderSide.
    shape = shape.copyWith(
      side: borderSide,
    );
565

566
    final double buttonTextScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 2.0);
567

568 569 570 571 572
    final Widget amButton = Material(
      color: MaterialStateProperty.resolveAs(backgroundColor, amStates),
      child: InkWell(
        onTap: Feedback.wrapForTap(() => _setAm(context), context),
        child: Semantics(
573 574
          checked: amSelected,
          inMutuallyExclusiveGroup: true,
575
          button: true,
576 577 578 579 580 581 582 583 584 585
          child: Center(
            child: Text(
              materialLocalizations.anteMeridiemAbbreviation,
              style: amStyle,
              textScaleFactor: buttonTextScaleFactor,
            ),
          ),
        ),
      ),
    );
586

587 588 589 590 591
    final Widget pmButton = Material(
      color: MaterialStateProperty.resolveAs(backgroundColor, pmStates),
      child: InkWell(
        onTap: Feedback.wrapForTap(() => _setPm(context), context),
        child: Semantics(
592 593
          checked: pmSelected,
          inMutuallyExclusiveGroup: true,
594
          button: true,
595 596 597 598 599 600 601 602 603 604
          child: Center(
            child: Text(
              materialLocalizations.postMeridiemAbbreviation,
              style: pmStyle,
              textScaleFactor: buttonTextScaleFactor,
            ),
          ),
        ),
      ),
    );
605

606
    final Widget result;
607 608
    switch (orientation) {
      case Orientation.portrait:
609 610 611 612
        const double width = 52.0;
        result = _DayPeriodInputPadding(
          minSize: const Size(width, kMinInteractiveDimension * 2),
          orientation: orientation,
613
          child: SizedBox(
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
            width: width,
            height: _kTimePickerHeaderControlHeight,
            child: Material(
              clipBehavior: Clip.antiAlias,
              color: Colors.transparent,
              shape: shape,
              child: Column(
                children: <Widget>[
                  Expanded(child: amButton),
                  Container(
                    decoration: BoxDecoration(
                      border: Border(top: borderSide),
                    ),
                    height: 1,
                  ),
                  Expanded(child: pmButton),
                ],
              ),
            ),
          ),
        );
Yegor's avatar
Yegor committed
635 636
        break;
      case Orientation.landscape:
637 638 639
        result = _DayPeriodInputPadding(
          minSize: const Size(0.0, kMinInteractiveDimension),
          orientation: orientation,
640
          child: SizedBox(
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
            height: 40.0,
            child: Material(
              clipBehavior: Clip.antiAlias,
              color: Colors.transparent,
              shape: shape,
              child: Row(
                children: <Widget>[
                  Expanded(child: amButton),
                  Container(
                    decoration: BoxDecoration(
                      border: Border(left: borderSide),
                    ),
                    width: 1,
                  ),
                  Expanded(child: pmButton),
                ],
              ),
            ),
          ),
        );
Yegor's avatar
Yegor committed
661 662
        break;
    }
663
    return result;
Yegor's avatar
Yegor committed
664
  }
665
}
666

667 668 669
/// A widget to pad the area around the [_DayPeriodControl]'s inner [Material].
class _DayPeriodInputPadding extends SingleChildRenderObjectWidget {
  const _DayPeriodInputPadding({
670 671 672 673
    Key? key,
    required Widget child,
    required this.minSize,
    required this.orientation,
674
  }) : super(key: key, child: child);
675

676 677
  final Size minSize;
  final Orientation orientation;
678

679 680 681
  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderInputPadding(minSize, orientation);
Yegor's avatar
Yegor committed
682
  }
683

684 685 686 687 688
  @override
  void updateRenderObject(BuildContext context, covariant _RenderInputPadding renderObject) {
    renderObject.minSize = minSize;
  }
}
689

690
class _RenderInputPadding extends RenderShiftedBox {
691
  _RenderInputPadding(this._minSize, this.orientation, [RenderBox? child]) : super(child);
692

693 694 695 696 697 698 699 700 701
  final Orientation orientation;

  Size get minSize => _minSize;
  Size _minSize;
  set minSize(Size value) {
    if (_minSize == value)
      return;
    _minSize = value;
    markNeedsLayout();
Yegor's avatar
Yegor committed
702
  }
703

704 705 706
  @override
  double computeMinIntrinsicWidth(double height) {
    if (child != null) {
707
      return math.max(child!.getMinIntrinsicWidth(height), minSize.width);
Yegor's avatar
Yegor committed
708
    }
709 710
    return 0.0;
  }
711

712 713 714
  @override
  double computeMinIntrinsicHeight(double width) {
    if (child != null) {
715
      return math.max(child!.getMinIntrinsicHeight(width), minSize.height);
Yegor's avatar
Yegor committed
716
    }
717
    return 0.0;
Yegor's avatar
Yegor committed
718
  }
719

720 721 722
  @override
  double computeMaxIntrinsicWidth(double height) {
    if (child != null) {
723
      return math.max(child!.getMaxIntrinsicWidth(height), minSize.width);
724
    }
725
    return 0.0;
726 727 728
  }

  @override
729 730
  double computeMaxIntrinsicHeight(double width) {
    if (child != null) {
731
      return math.max(child!.getMaxIntrinsicHeight(width), minSize.height);
732 733
    }
    return 0.0;
734 735
  }

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
  Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) {
    if (child != null) {
      final Size childSize = layoutChild(child!, constraints);
      final double width = math.max(childSize.width, minSize.width);
      final double height = math.max(childSize.height, minSize.height);
      return constraints.constrain(Size(width, height));
    }
    return Size.zero;
  }

  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return _computeSize(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.dryLayoutChild,
    );
  }

754 755
  @override
  void performLayout() {
756 757 758 759
    size = _computeSize(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.layoutChild,
    );
760
    if (child != null) {
761 762
      final BoxParentData childParentData = child!.parentData! as BoxParentData;
      childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset);
763 764 765
    }
  }

766
  @override
767
  bool hitTest(BoxHitTestResult result, { required Offset position }) {
768 769 770
    if (super.hitTest(result, position: position)) {
      return true;
    }
Yegor's avatar
Yegor committed
771

772
    if (position.dx < 0.0 ||
773
        position.dx > math.max(child!.size.width, minSize.width) ||
774
        position.dy < 0.0 ||
775
        position.dy > math.max(child!.size.height, minSize.height)) {
776 777
      return false;
    }
Yegor's avatar
Yegor committed
778

779
    Offset newPosition = child!.size.center(Offset.zero);
Yegor's avatar
Yegor committed
780 781
    switch (orientation) {
      case Orientation.portrait:
782 783 784 785 786
        if (position.dy > newPosition.dy) {
          newPosition += const Offset(0.0, 1.0);
        } else {
          newPosition += const Offset(0.0, -1.0);
        }
787
        break;
Yegor's avatar
Yegor committed
788
      case Orientation.landscape:
789 790 791 792 793
        if (position.dx > newPosition.dx) {
          newPosition += const Offset(1.0, 0.0);
        } else {
          newPosition += const Offset(-1.0, 0.0);
        }
794 795
        break;
    }
796 797


798 799 800 801 802
    return result.addWithRawTransform(
      transform: MatrixUtils.forceToPoint(newPosition),
      position: newPosition,
      hitTest: (BoxHitTestResult result, Offset position) {
        assert(position == newPosition);
803
        return child!.hitTest(result, position: newPosition);
804
      },
805
    );
806 807
  }
}
808

809 810
class _TappableLabel {
  _TappableLabel({
811 812 813
    required this.value,
    required this.painter,
    required this.onTap,
814 815 816 817 818 819 820 821 822 823 824 825
  });

  /// The value this label is displaying.
  final int value;

  /// Paints the text of the label.
  final TextPainter painter;

  /// Called when a tap gesture is detected on the label.
  final VoidCallback onTap;
}

826
class _DialPainter extends CustomPainter {
827
  _DialPainter({
828 829 830 831 832 833 834 835
    required this.primaryLabels,
    required this.secondaryLabels,
    required this.backgroundColor,
    required this.accentColor,
    required this.dotColor,
    required this.theta,
    required this.textDirection,
    required this.selectedValue,
836
  }) : super(repaint: PaintingBinding.instance!.systemFonts);
837

838 839
  final List<_TappableLabel> primaryLabels;
  final List<_TappableLabel> secondaryLabels;
840 841
  final Color backgroundColor;
  final Color accentColor;
842
  final Color dotColor;
843
  final double theta;
844 845
  final TextDirection textDirection;
  final int selectedValue;
846

847 848
  static const double _labelPadding = 28.0;

849
  @override
850
  void paint(Canvas canvas, Size size) {
851
    final double radius = size.shortestSide / 2.0;
852
    final Offset center = Offset(size.width / 2.0, size.height / 2.0);
853
    final Offset centerPoint = center;
854
    canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor);
855

856 857 858
    final double labelRadius = radius - _labelPadding;
    Offset getOffsetForTheta(double theta) {
      return center + Offset(labelRadius * math.cos(theta), -labelRadius * math.sin(theta));
859 860
    }

861
    void paintLabels(List<_TappableLabel>? labels) {
Yegor's avatar
Yegor committed
862 863
      if (labels == null)
        return;
864
      final double labelThetaIncrement = -_kTwoPi / labels.length;
865
      double labelTheta = math.pi / 2.0;
866

867
      for (final _TappableLabel label in labels) {
868 869 870
        final TextPainter labelPainter = label.painter;
        final Offset labelOffset = Offset(-labelPainter.width / 2.0, -labelPainter.height / 2.0);
        labelPainter.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset);
871 872 873 874
        labelTheta += labelThetaIncrement;
      }
    }

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    paintLabels(primaryLabels);

    final Paint selectorPaint = Paint()
      ..color = accentColor;
    final Offset focusedPoint = getOffsetForTheta(theta);
    const double focusedRadius = _labelPadding - 4.0;
    canvas.drawCircle(centerPoint, 4.0, selectorPaint);
    canvas.drawCircle(focusedPoint, focusedRadius, selectorPaint);
    selectorPaint.strokeWidth = 2.0;
    canvas.drawLine(centerPoint, focusedPoint, selectorPaint);

    // Add a dot inside the selector but only when it isn't over the labels.
    // This checks that the selector's theta is between two labels. A remainder
    // between 0.1 and 0.45 indicates that the selector is roughly not above any
    // labels. The values were derived by manually testing the dial.
    final double labelThetaIncrement = -_kTwoPi / primaryLabels.length;
    if (theta % labelThetaIncrement > 0.1 && theta % labelThetaIncrement < 0.45) {
      canvas.drawCircle(focusedPoint, 2.0, selectorPaint..color = dotColor);
    }
894

895 896 897 898 899 900 901 902
    final Rect focusedRect = Rect.fromCircle(
      center: focusedPoint, radius: focusedRadius,
    );
    canvas
      ..save()
      ..clipPath(Path()..addOval(focusedRect));
    paintLabels(secondaryLabels);
    canvas.restore();
903 904
  }

905
  @override
906
  bool shouldRepaint(_DialPainter oldPainter) {
907 908
    return oldPainter.primaryLabels != primaryLabels
        || oldPainter.secondaryLabels != secondaryLabels
909 910
        || oldPainter.backgroundColor != backgroundColor
        || oldPainter.accentColor != accentColor
911
        || oldPainter.theta != theta;
912 913 914
  }
}

915
class _Dial extends StatefulWidget {
916
  const _Dial({
917 918 919 920 921
    required this.selectedTime,
    required this.mode,
    required this.use24HourDials,
    required this.onChanged,
    required this.onHourSelected,
922 923 924
  }) : assert(selectedTime != null),
       assert(mode != null),
       assert(use24HourDials != null);
925 926 927

  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
928
  final bool use24HourDials;
929
  final ValueChanged<TimeOfDay>? onChanged;
930
  final VoidCallback? onHourSelected;
931

932
  @override
933
  _DialState createState() => _DialState();
934 935
}

936
class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
937
  @override
938 939
  void initState() {
    super.initState();
940
    _thetaController = AnimationController(
941 942 943
      duration: _kDialAnimateDuration,
      vsync: this,
    );
944
    _thetaTween = Tween<double>(begin: _getThetaForTime(widget.selectedTime));
945
    _theta = _thetaController
946
      .drive(CurveTween(curve: standardEasing))
947 948
      .drive(_thetaTween)
      ..addListener(() => setState(() { /* _theta.value has changed */ }));
949 950
  }

951 952 953
  late ThemeData themeData;
  late MaterialLocalizations localizations;
  late MediaQueryData media;
954 955 956 957 958

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    assert(debugCheckHasMediaQuery(context));
959
    themeData = Theme.of(context);
960
    localizations = MaterialLocalizations.of(context);
961
    media = MediaQuery.of(context);
962 963
  }

964
  @override
965
  void didUpdateWidget(_Dial oldWidget) {
966
    super.didUpdateWidget(oldWidget);
967
    if (widget.mode != oldWidget.mode || widget.selectedTime != oldWidget.selectedTime) {
Yegor's avatar
Yegor committed
968 969 970
      if (!_dragging)
        _animateTo(_getThetaForTime(widget.selectedTime));
    }
971 972
  }

973 974 975 976 977 978
  @override
  void dispose() {
    _thetaController.dispose();
    super.dispose();
  }

979 980 981
  late Tween<double> _thetaTween;
  late Animation<double> _theta;
  late AnimationController _thetaController;
Adam Barth's avatar
Adam Barth committed
982 983 984 985 986 987 988
  bool _dragging = false;

  static double _nearest(double target, double a, double b) {
    return ((target - a).abs() < (target - b).abs()) ? a : b;
  }

  void _animateTo(double targetTheta) {
989
    final double currentTheta = _theta.value;
Adam Barth's avatar
Adam Barth committed
990 991
    double beginTheta = _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi);
    beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi);
992 993 994 995 996 997
    _thetaTween
      ..begin = beginTheta
      ..end = targetTheta;
    _thetaController
      ..value = 0.0
      ..forward();
998 999 1000
  }

  double _getThetaForTime(TimeOfDay time) {
1001
    final int hoursFactor = widget.use24HourDials ? TimeOfDay.hoursPerDay : TimeOfDay.hoursPerPeriod;
1002
    final double fraction = widget.mode == _TimePickerMode.hour
1003
      ? (time.hour / hoursFactor) % hoursFactor
1004
      : (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour;
1005
    return (math.pi / 2.0 - fraction * _kTwoPi) % _kTwoPi;
1006 1007
  }

1008
  TimeOfDay _getTimeForTheta(double theta, {bool roundMinutes = false}) {
1009
    final double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0;
1010
    if (widget.mode == _TimePickerMode.hour) {
1011
      int newHour;
1012
      if (widget.use24HourDials) {
1013
        newHour = (fraction * TimeOfDay.hoursPerDay).round() % TimeOfDay.hoursPerDay;
Yegor's avatar
Yegor committed
1014
      } else {
1015
        newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % TimeOfDay.hoursPerPeriod;
Yegor's avatar
Yegor committed
1016 1017 1018
        newHour = newHour + widget.selectedTime.periodOffset;
      }
      return widget.selectedTime.replacing(hour: newHour);
1019
    } else {
1020 1021 1022 1023 1024 1025
      int minute = (fraction * TimeOfDay.minutesPerHour).round() % TimeOfDay.minutesPerHour;
      if (roundMinutes) {
        // Round the minutes to nearest 5 minute interval.
        minute = ((minute + 2) ~/ 5) * 5 % TimeOfDay.minutesPerHour;
      }
      return widget.selectedTime.replacing(minute: minute);
1026 1027 1028
    }
  }

1029 1030
  TimeOfDay _notifyOnChangedIfNeeded({ bool roundMinutes = false }) {
    final TimeOfDay current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes);
1031 1032
    if (widget.onChanged == null)
      return current;
1033
    if (current != widget.selectedTime)
1034
      widget.onChanged!(current);
1035
    return current;
1036 1037
  }

1038
  void _updateThetaForPan({ bool roundMinutes = false }) {
1039
    setState(() {
1040
      final Offset offset = _position! - _center!;
1041 1042 1043 1044
      double angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2.0) % _kTwoPi;
      if (roundMinutes) {
        angle = _getThetaForTime(_getTimeForTheta(angle, roundMinutes: roundMinutes));
      }
1045
      _thetaTween
Hans Muller's avatar
Hans Muller committed
1046 1047
        ..begin = angle
        ..end = angle; // The controller doesn't animate during the pan gesture.
1048 1049 1050
    });
  }

1051 1052
  Offset? _position;
  Offset? _center;
1053

1054
  void _handlePanStart(DragStartDetails details) {
Adam Barth's avatar
Adam Barth committed
1055 1056
    assert(!_dragging);
    _dragging = true;
1057
    final RenderBox box = context.findRenderObject()! as RenderBox;
1058
    _position = box.globalToLocal(details.globalPosition);
1059
    _center = box.size.center(Offset.zero);
1060 1061 1062 1063
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

1064
  void _handlePanUpdate(DragUpdateDetails details) {
1065
    _position = _position! + details.delta;
1066 1067 1068 1069
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

1070
  void _handlePanEnd(DragEndDetails details) {
Adam Barth's avatar
Adam Barth committed
1071 1072
    assert(_dragging);
    _dragging = false;
1073 1074
    _position = null;
    _center = null;
1075
    _animateTo(_getThetaForTime(widget.selectedTime));
1076
    if (widget.mode == _TimePickerMode.hour) {
1077
      widget.onHourSelected?.call();
1078
    }
1079 1080
  }

1081
  void _handleTapUp(TapUpDetails details) {
1082
    final RenderBox box = context.findRenderObject()! as RenderBox;
1083 1084
    _position = box.globalToLocal(details.globalPosition);
    _center = box.size.center(Offset.zero);
1085 1086
    _updateThetaForPan(roundMinutes: true);
    final TimeOfDay newTime = _notifyOnChangedIfNeeded(roundMinutes: true);
1087 1088 1089 1090 1091 1092
    if (widget.mode == _TimePickerMode.hour) {
      if (widget.use24HourDials) {
        _announceToAccessibility(context, localizations.formatDecimal(newTime.hour));
      } else {
        _announceToAccessibility(context, localizations.formatDecimal(newTime.hourOfPeriod));
      }
1093
      widget.onHourSelected?.call();
1094 1095 1096
    } else {
      _announceToAccessibility(context, localizations.formatDecimal(newTime.minute));
    }
1097
    _animateTo(_getThetaForTime(_getTimeForTheta(_theta.value, roundMinutes: true)));
1098 1099 1100 1101 1102 1103 1104
    _dragging = false;
    _position = null;
    _center = null;
  }

  void _selectHour(int hour) {
    _announceToAccessibility(context, localizations.formatDecimal(hour));
1105
    final TimeOfDay time;
1106
    if (widget.mode == _TimePickerMode.hour && widget.use24HourDials) {
1107
      time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute);
1108 1109
    } else {
      if (widget.selectedTime.period == DayPeriod.am) {
1110
        time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute);
1111
      } else {
1112
        time = TimeOfDay(hour: hour + TimeOfDay.hoursPerPeriod, minute: widget.selectedTime.minute);
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
      }
    }
    final double angle = _getThetaForTime(time);
    _thetaTween
      ..begin = angle
      ..end = angle;
    _notifyOnChangedIfNeeded();
  }

  void _selectMinute(int minute) {
    _announceToAccessibility(context, localizations.formatDecimal(minute));
1124
    final TimeOfDay time = TimeOfDay(
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
      hour: widget.selectedTime.hour,
      minute: minute,
    );
    final double angle = _getThetaForTime(time);
    _thetaTween
      ..begin = angle
      ..end = angle;
    _notifyOnChangedIfNeeded();
  }

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  static const List<TimeOfDay> _amHours = <TimeOfDay>[
    TimeOfDay(hour: 12, minute: 0),
    TimeOfDay(hour: 1, minute: 0),
    TimeOfDay(hour: 2, minute: 0),
    TimeOfDay(hour: 3, minute: 0),
    TimeOfDay(hour: 4, minute: 0),
    TimeOfDay(hour: 5, minute: 0),
    TimeOfDay(hour: 6, minute: 0),
    TimeOfDay(hour: 7, minute: 0),
    TimeOfDay(hour: 8, minute: 0),
    TimeOfDay(hour: 9, minute: 0),
    TimeOfDay(hour: 10, minute: 0),
    TimeOfDay(hour: 11, minute: 0),
1148 1149
  ];

1150
  static const List<TimeOfDay> _twentyFourHours = <TimeOfDay>[
1151
    TimeOfDay(hour: 0, minute: 0),
1152 1153 1154 1155 1156 1157
    TimeOfDay(hour: 2, minute: 0),
    TimeOfDay(hour: 4, minute: 0),
    TimeOfDay(hour: 6, minute: 0),
    TimeOfDay(hour: 8, minute: 0),
    TimeOfDay(hour: 10, minute: 0),
    TimeOfDay(hour: 12, minute: 0),
1158 1159 1160 1161 1162
    TimeOfDay(hour: 14, minute: 0),
    TimeOfDay(hour: 16, minute: 0),
    TimeOfDay(hour: 18, minute: 0),
    TimeOfDay(hour: 20, minute: 0),
    TimeOfDay(hour: 22, minute: 0),
1163 1164
  ];

1165
  _TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, int value, String label, VoidCallback onTap) {
1166
    final TextStyle style = textTheme.bodyText1!.copyWith(color: color);
1167
    final double labelScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 2.0);
1168
    return _TappableLabel(
1169
      value: value,
1170 1171
      painter: TextPainter(
        text: TextSpan(style: style, text: label),
1172
        textDirection: TextDirection.ltr,
1173
        textScaleFactor: labelScaleFactor,
1174 1175 1176
      )..layout(),
      onTap: onTap,
    );
1177 1178
  }

1179
  List<_TappableLabel> _build24HourRing(TextTheme textTheme, Color color) => <_TappableLabel>[
1180
    for (final TimeOfDay timeOfDay in _twentyFourHours)
1181
      _buildTappableLabel(
1182
        textTheme,
1183
        color,
1184 1185 1186 1187 1188
        timeOfDay.hour,
        localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
        () {
          _selectHour(timeOfDay.hour);
        },
1189 1190
      ),
  ];
1191

1192
  List<_TappableLabel> _build12HourRing(TextTheme textTheme, Color color) => <_TappableLabel>[
1193
    for (final TimeOfDay timeOfDay in _amHours)
1194
      _buildTappableLabel(
1195
        textTheme,
1196
        color,
1197 1198 1199 1200 1201
        timeOfDay.hour,
        localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
        () {
          _selectHour(timeOfDay.hour);
        },
1202 1203
      ),
  ];
1204

1205
  List<_TappableLabel> _buildMinutes(TextTheme textTheme, Color color) {
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    const List<TimeOfDay> _minuteMarkerValues = <TimeOfDay>[
      TimeOfDay(hour: 0, minute: 0),
      TimeOfDay(hour: 0, minute: 5),
      TimeOfDay(hour: 0, minute: 10),
      TimeOfDay(hour: 0, minute: 15),
      TimeOfDay(hour: 0, minute: 20),
      TimeOfDay(hour: 0, minute: 25),
      TimeOfDay(hour: 0, minute: 30),
      TimeOfDay(hour: 0, minute: 35),
      TimeOfDay(hour: 0, minute: 40),
      TimeOfDay(hour: 0, minute: 45),
      TimeOfDay(hour: 0, minute: 50),
      TimeOfDay(hour: 0, minute: 55),
1219 1220
    ];

1221
    return <_TappableLabel>[
1222
      for (final TimeOfDay timeOfDay in _minuteMarkerValues)
1223 1224
        _buildTappableLabel(
          textTheme,
1225
          color,
1226 1227 1228 1229 1230 1231 1232
          timeOfDay.minute,
          localizations.formatMinute(timeOfDay),
          () {
            _selectMinute(timeOfDay.minute);
          },
        ),
    ];
1233 1234
  }

1235
  @override
1236
  Widget build(BuildContext context) {
1237
    final ThemeData theme = Theme.of(context);
1238 1239 1240
    final TimePickerThemeData pickerTheme = TimePickerTheme.of(context);
    final Color backgroundColor = pickerTheme.dialBackgroundColor ?? themeData.colorScheme.onBackground.withOpacity(0.12);
    final Color accentColor = pickerTheme.dialHandColor ?? themeData.colorScheme.primary;
1241 1242
    final Color primaryLabelColor = MaterialStateProperty.resolveAs(pickerTheme.dialTextColor, <MaterialState>{}) ?? themeData.colorScheme.onSurface;
    final Color secondaryLabelColor = MaterialStateProperty.resolveAs(pickerTheme.dialTextColor, <MaterialState>{MaterialState.selected}) ?? themeData.colorScheme.onPrimary;
1243 1244
    List<_TappableLabel> primaryLabels;
    List<_TappableLabel> secondaryLabels;
1245
    final int selectedDialValue;
1246
    switch (widget.mode) {
1247
      case _TimePickerMode.hour:
1248
        if (widget.use24HourDials) {
1249
          selectedDialValue = widget.selectedTime.hour;
1250
          primaryLabels = _build24HourRing(theme.textTheme, primaryLabelColor);
1251
          secondaryLabels = _build24HourRing(theme.textTheme, secondaryLabelColor);
1252
        } else {
1253
          selectedDialValue = widget.selectedTime.hourOfPeriod;
1254
          primaryLabels = _build12HourRing(theme.textTheme, primaryLabelColor);
1255
          secondaryLabels = _build12HourRing(theme.textTheme, secondaryLabelColor);
1256
        }
1257 1258
        break;
      case _TimePickerMode.minute:
1259
        selectedDialValue = widget.selectedTime.minute;
1260
        primaryLabels = _buildMinutes(theme.textTheme, primaryLabelColor);
1261
        secondaryLabels = _buildMinutes(theme.textTheme, secondaryLabelColor);
1262 1263 1264
        break;
    }

1265
    return GestureDetector(
1266
      excludeFromSemantics: true,
1267 1268 1269
      onPanStart: _handlePanStart,
      onPanUpdate: _handlePanUpdate,
      onPanEnd: _handlePanEnd,
1270
      onTapUp: _handleTapUp,
1271
      child: CustomPaint(
1272
        key: const ValueKey<String>('time-picker-dial'),
1273
        painter: _DialPainter(
1274
          selectedValue: selectedDialValue,
1275 1276
          primaryLabels: primaryLabels,
          secondaryLabels: secondaryLabels,
1277
          backgroundColor: backgroundColor,
1278 1279
          accentColor: accentColor,
          dotColor: theme.colorScheme.surface,
Yegor's avatar
Yegor committed
1280
          theta: _theta.value,
1281
          textDirection: Directionality.of(context),
1282
        ),
1283
      ),
1284 1285 1286
    );
  }
}
1287

1288 1289
class _TimePickerInput extends StatefulWidget {
  const _TimePickerInput({
1290 1291 1292
    Key? key,
    required this.initialSelectedTime,
    required this.helpText,
1293 1294 1295
    required this.errorInvalidText,
    required this.hourLabelText,
    required this.minuteLabelText,
1296 1297 1298
    required this.autofocusHour,
    required this.autofocusMinute,
    required this.onChanged,
1299
    this.restorationId,
1300 1301 1302 1303 1304 1305 1306 1307
  }) : assert(initialSelectedTime != null),
       assert(onChanged != null),
       super(key: key);

  /// The time initially selected when the dialog is shown.
  final TimeOfDay initialSelectedTime;

  /// Optionally provide your own help text to the time picker.
1308
  final String? helpText;
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318
  /// Optionally provide your own validation error text.
  final String? errorInvalidText;

  /// Optionally provide your own hour label text.
  final String? hourLabelText;

  /// Optionally provide your own minute label text.
  final String? minuteLabelText;

1319
  final bool? autofocusHour;
1320

1321
  final bool? autofocusMinute;
1322

1323 1324
  final ValueChanged<TimeOfDay> onChanged;

1325 1326 1327 1328 1329 1330 1331 1332 1333
  /// Restoration ID to save and restore the state of the time picker input
  /// widget.
  ///
  /// If it is non-null, the widget will persist and restore its state
  ///
  /// The state of this widget is persisted in a [RestorationBucket] claimed
  /// from the surrounding [RestorationScope] using the provided restoration ID.
  final String? restorationId;

1334 1335 1336 1337
  @override
  _TimePickerInputState createState() => _TimePickerInputState();
}

1338 1339 1340 1341
class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixin {
  late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.initialSelectedTime);
  final RestorableBool hourHasError = RestorableBool(false);
  final RestorableBool minuteHasError = RestorableBool(false);
1342 1343

  @override
1344 1345 1346 1347 1348 1349 1350
  String? get restorationId => widget.restorationId;

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(_selectedTime, 'selected_time');
    registerForRestoration(hourHasError, 'hour_has_error');
    registerForRestoration(minuteHasError, 'minute_has_error');
1351 1352
  }

1353
  int? _parseHour(String? value) {
1354 1355 1356 1357
    if (value == null) {
      return null;
    }

1358
    int? newHour = int.tryParse(value);
1359 1360 1361 1362
    if (newHour == null) {
      return null;
    }

1363
    if (MediaQuery.of(context).alwaysUse24HourFormat) {
1364 1365 1366 1367 1368
      if (newHour >= 0 && newHour < 24) {
        return newHour;
      }
    } else {
      if (newHour > 0 && newHour < 13) {
1369 1370
        if ((_selectedTime.value.period == DayPeriod.pm && newHour != 12)
            || (_selectedTime.value.period == DayPeriod.am && newHour == 12)) {
1371 1372 1373 1374 1375 1376 1377 1378
          newHour = (newHour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay;
        }
        return newHour;
      }
    }
    return null;
  }

1379
  int? _parseMinute(String? value) {
1380 1381 1382 1383
    if (value == null) {
      return null;
    }

1384
    final int? newMinute = int.tryParse(value);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
    if (newMinute == null) {
      return null;
    }

    if (newMinute >= 0 && newMinute < 60) {
      return newMinute;
    }
    return null;
  }

1395 1396
  void _handleHourSavedSubmitted(String? value) {
    final int? newHour = _parseHour(value);
1397
    if (newHour != null) {
1398 1399
      _selectedTime.value = TimeOfDay(hour: newHour, minute: _selectedTime.value.minute);
      widget.onChanged(_selectedTime.value);
1400 1401 1402 1403
    }
  }

  void _handleHourChanged(String value) {
1404
    final int? newHour = _parseHour(value);
1405 1406 1407 1408 1409 1410
    if (newHour != null && value.length == 2) {
      // If a valid hour is typed, move focus to the minute TextField.
      FocusScope.of(context).nextFocus();
    }
  }

1411 1412
  void _handleMinuteSavedSubmitted(String? value) {
    final int? newMinute = _parseMinute(value);
1413
    if (newMinute != null) {
1414 1415
      _selectedTime.value = TimeOfDay(hour: _selectedTime.value.hour, minute: int.parse(value!));
      widget.onChanged(_selectedTime.value);
1416 1417 1418 1419
    }
  }

  void _handleDayPeriodChanged(TimeOfDay value) {
1420 1421
    _selectedTime.value = value;
    widget.onChanged(_selectedTime.value);
1422 1423
  }

1424 1425
  String? _validateHour(String? value) {
    final int? newHour = _parseHour(value);
1426
    setState(() {
1427
      hourHasError.value = newHour == null;
1428 1429 1430 1431 1432 1433 1434
    });
    // This is used as the validator for the [TextFormField].
    // Returning an empty string allows the field to go into an error state.
    // Returning null means no error in the validation of the entered text.
    return newHour == null ? '' : null;
  }

1435 1436
  String? _validateMinute(String? value) {
    final int? newMinute = _parseMinute(value);
1437
    setState(() {
1438
      minuteHasError.value = newMinute == null;
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    });
    // This is used as the validator for the [TextFormField].
    // Returning an empty string allows the field to go into an error state.
    // Returning null means no error in the validation of the entered text.
    return newMinute == null ? '' : null;
  }

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMediaQuery(context));
1449
    final MediaQueryData media = MediaQuery.of(context);
1450
    final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
1451
    final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
1452
    final ThemeData theme = Theme.of(context);
1453
    final TextStyle hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? theme.textTheme.headline2!;
1454 1455 1456 1457 1458 1459 1460

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
1461
            widget.helpText ?? MaterialLocalizations.of(context).timePickerInputHelpText,
1462 1463 1464 1465 1466 1467 1468 1469
            style: TimePickerTheme.of(context).helpTextStyle ?? theme.textTheme.overline,
          ),
          const SizedBox(height: 16.0),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              if (!use24HourDials && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                _DayPeriodControl(
1470
                  selectedTime: _selectedTime.value,
1471 1472 1473 1474 1475
                  orientation: Orientation.portrait,
                  onChanged: _handleDayPeriodChanged,
                ),
                const SizedBox(width: 12.0),
              ],
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
              Expanded(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  // Hour/minutes should not change positions in RTL locales.
                  textDirection: TextDirection.ltr,
                  children: <Widget>[
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          const SizedBox(height: 8.0),
                          _HourTextField(
1488 1489
                            restorationId: 'hour_text_field',
                            selectedTime: _selectedTime.value,
1490
                            style: hourMinuteStyle,
1491
                            autofocus: widget.autofocusHour,
1492 1493 1494
                            validator: _validateHour,
                            onSavedSubmitted: _handleHourSavedSubmitted,
                            onChanged: _handleHourChanged,
1495
                            hourLabelText: widget.hourLabelText,
1496 1497
                          ),
                          const SizedBox(height: 8.0),
1498
                          if (!hourHasError.value && !minuteHasError.value)
1499 1500
                            ExcludeSemantics(
                              child: Text(
1501
                                widget.hourLabelText ?? MaterialLocalizations.of(context).timePickerHourLabel,
1502 1503 1504 1505 1506 1507
                                style: theme.textTheme.caption,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                        ],
1508
                      ),
1509
                    ),
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
                    Container(
                      margin: const EdgeInsets.only(top: 8.0),
                      height: _kTimePickerHeaderControlHeight,
                      child: _StringFragment(timeOfDayFormat: timeOfDayFormat),
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          const SizedBox(height: 8.0),
                          _MinuteTextField(
1521 1522
                            restorationId: 'minute_text_field',
                            selectedTime: _selectedTime.value,
1523
                            style: hourMinuteStyle,
1524
                            autofocus: widget.autofocusMinute,
1525 1526
                            validator: _validateMinute,
                            onSavedSubmitted: _handleMinuteSavedSubmitted,
1527
                            minuteLabelText: widget.minuteLabelText,
1528 1529
                          ),
                          const SizedBox(height: 8.0),
1530
                          if (!hourHasError.value && !minuteHasError.value)
1531 1532
                            ExcludeSemantics(
                              child: Text(
1533
                                widget.minuteLabelText ?? MaterialLocalizations.of(context).timePickerMinuteLabel,
1534 1535 1536 1537 1538 1539
                                style: theme.textTheme.caption,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                        ],
1540
                      ),
1541
                    ),
1542 1543 1544
                  ],
                ),
              ),
1545 1546 1547
              if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                const SizedBox(width: 12.0),
                _DayPeriodControl(
1548
                  selectedTime: _selectedTime.value,
1549 1550 1551 1552 1553 1554
                  orientation: Orientation.portrait,
                  onChanged: _handleDayPeriodChanged,
                ),
              ],
            ],
          ),
1555
          if (hourHasError.value || minuteHasError.value)
1556
            Text(
1557
              widget.errorInvalidText ?? MaterialLocalizations.of(context).invalidTimeLabel,
1558
              style: theme.textTheme.bodyText2!.copyWith(color: theme.colorScheme.error),
1559 1560 1561 1562 1563 1564 1565 1566 1567
            )
          else
            const SizedBox(height: 2.0),
        ],
      ),
    );
  }
}

1568 1569
class _HourTextField extends StatelessWidget {
  const _HourTextField({
1570 1571 1572 1573 1574 1575 1576
    Key? key,
    required this.selectedTime,
    required this.style,
    required this.autofocus,
    required this.validator,
    required this.onSavedSubmitted,
    required this.onChanged,
1577
    required this.hourLabelText,
1578
    this.restorationId,
1579 1580 1581 1582
  }) : super(key: key);

  final TimeOfDay selectedTime;
  final TextStyle style;
1583
  final bool? autofocus;
1584
  final FormFieldValidator<String> validator;
1585
  final ValueChanged<String?> onSavedSubmitted;
1586
  final ValueChanged<String> onChanged;
1587
  final String? hourLabelText;
1588
  final String? restorationId;
1589 1590 1591 1592

  @override
  Widget build(BuildContext context) {
    return _HourMinuteTextField(
1593
      restorationId: restorationId,
1594 1595
      selectedTime: selectedTime,
      isHour: true,
1596
      autofocus: autofocus,
1597
      style: style,
1598
      semanticHintText: hourLabelText ??  MaterialLocalizations.of(context).timePickerHourLabel,
1599 1600 1601 1602 1603 1604 1605 1606 1607
      validator: validator,
      onSavedSubmitted: onSavedSubmitted,
      onChanged: onChanged,
    );
  }
}

class _MinuteTextField extends StatelessWidget {
  const _MinuteTextField({
1608 1609 1610 1611 1612 1613
    Key? key,
    required this.selectedTime,
    required this.style,
    required this.autofocus,
    required this.validator,
    required this.onSavedSubmitted,
1614
    required this.minuteLabelText,
1615
    this.restorationId,
1616 1617 1618 1619
  }) : super(key: key);

  final TimeOfDay selectedTime;
  final TextStyle style;
1620
  final bool? autofocus;
1621
  final FormFieldValidator<String> validator;
1622
  final ValueChanged<String?> onSavedSubmitted;
1623
  final String? minuteLabelText;
1624
  final String? restorationId;
1625 1626 1627 1628

  @override
  Widget build(BuildContext context) {
    return _HourMinuteTextField(
1629
      restorationId: restorationId,
1630 1631
      selectedTime: selectedTime,
      isHour: false,
1632
      autofocus: autofocus,
1633
      style: style,
1634
      semanticHintText: minuteLabelText ?? MaterialLocalizations.of(context).timePickerMinuteLabel,
1635 1636 1637 1638 1639 1640
      validator: validator,
      onSavedSubmitted: onSavedSubmitted,
    );
  }
}

1641 1642
class _HourMinuteTextField extends StatefulWidget {
  const _HourMinuteTextField({
1643 1644 1645 1646 1647 1648 1649 1650
    Key? key,
    required this.selectedTime,
    required this.isHour,
    required this.autofocus,
    required this.style,
    required this.semanticHintText,
    required this.validator,
    required this.onSavedSubmitted,
1651
    this.restorationId,
1652 1653 1654 1655 1656
    this.onChanged,
  }) : super(key: key);

  final TimeOfDay selectedTime;
  final bool isHour;
1657
  final bool? autofocus;
1658
  final TextStyle style;
1659
  final String semanticHintText;
1660
  final FormFieldValidator<String> validator;
1661 1662
  final ValueChanged<String?> onSavedSubmitted;
  final ValueChanged<String>? onChanged;
1663
  final String? restorationId;
1664 1665 1666 1667 1668

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

1669 1670 1671
class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with RestorationMixin {
  final RestorableTextEditingController controller = RestorableTextEditingController();
  final RestorableBool controllerHasBeenSet = RestorableBool(false);
1672
  late FocusNode focusNode;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684

  @override
  void initState() {
    super.initState();
    focusNode = FocusNode()..addListener(() {
      setState(() { }); // Rebuild.
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
    // Only set the text value if it has not been populated with a localized
    // version yet.
    if (!controllerHasBeenSet.value) {
      controllerHasBeenSet.value = true;
      controller.value.text = _formattedValue;
    }
  }

  @override
  String? get restorationId => widget.restorationId;

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(controller, 'text_editing_controller');
    registerForRestoration(controllerHasBeenSet, 'has_controller_been_set');
1700 1701 1702
  }

  String get _formattedValue {
1703
    final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat;
1704
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
1705 1706 1707 1708 1709 1710 1711 1712
    return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour(
      widget.selectedTime,
      alwaysUse24HourFormat: alwaysUse24HourFormat,
    );
  }

  @override
  Widget build(BuildContext context) {
1713
    final ThemeData theme = Theme.of(context);
1714
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
1715 1716
    final ColorScheme colorScheme = theme.colorScheme;

1717
    final InputDecorationTheme? inputDecorationTheme = timePickerTheme.inputDecorationTheme;
1718 1719 1720 1721 1722
    InputDecoration inputDecoration;
    if (inputDecorationTheme != null) {
      inputDecoration = const InputDecoration().applyDefaults(inputDecorationTheme);
    } else {
      inputDecoration = InputDecoration(
1723
        contentPadding: EdgeInsets.zero,
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
        filled: true,
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Colors.transparent),
        ),
        errorBorder: OutlineInputBorder(
          borderSide: BorderSide(color: colorScheme.error, width: 2.0),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: colorScheme.primary, width: 2.0),
        ),
        focusedErrorBorder: OutlineInputBorder(
          borderSide: BorderSide(color: colorScheme.error, width: 2.0),
        ),
        hintStyle: widget.style.copyWith(color: colorScheme.onSurface.withOpacity(0.36)),
        // TODO(rami-a): Remove this logic once https://github.com/flutter/flutter/issues/54104 is fixed.
        errorStyle: const TextStyle(fontSize: 0.0, height: 0.0), // Prevent the error text from appearing.
      );
    }
1742
    final Color unfocusedFillColor = timePickerTheme.hourMinuteColor ?? colorScheme.onSurface.withOpacity(0.12);
1743 1744 1745
    // If screen reader is in use, make the hint text say hours/minutes.
    // Otherwise, remove the hint text when focused because the centered cursor
    // appears odd above the hint text.
1746 1747 1748
    //
    // TODO(rami-a): Once https://github.com/flutter/flutter/issues/67571 is
    // resolved, remove the window check for semantics being enabled on web.
1749
    final String? hintText = MediaQuery.of(context).accessibleNavigation || ui.window.semanticsEnabled
1750 1751
        ? widget.semanticHintText
        : (focusNode.hasFocus ? null : _formattedValue);
1752
    inputDecoration = inputDecoration.copyWith(
1753
      hintText: hintText,
1754
      fillColor: focusNode.hasFocus ? Colors.transparent : inputDecorationTheme?.fillColor ?? unfocusedFillColor,
1755 1756
    );

1757 1758 1759
    return SizedBox(
      height: _kTimePickerHeaderControlHeight,
      child: MediaQuery(
1760
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
        child: UnmanagedRestorationScope(
          bucket: bucket,
          child: TextFormField(
            restorationId: 'hour_minute_text_form_field',
            autofocus: widget.autofocus ?? false,
            expands: true,
            maxLines: null,
            inputFormatters: <TextInputFormatter>[
              LengthLimitingTextInputFormatter(2),
            ],
            focusNode: focusNode,
            textAlign: TextAlign.center,
            keyboardType: TextInputType.number,
            style: widget.style.copyWith(color: timePickerTheme.hourMinuteTextColor ?? colorScheme.onSurface),
            controller: controller.value,
            decoration: inputDecoration,
            validator: widget.validator,
            onEditingComplete: () => widget.onSavedSubmitted(controller.value.text),
            onSaved: widget.onSavedSubmitted,
            onFieldSubmitted: widget.onSavedSubmitted,
            onChanged: widget.onChanged,
          ),
1783
        ),
1784
      ),
1785 1786 1787 1788
    );
  }
}

1789 1790 1791
/// Signature for when the time picker entry mode is changed.
typedef EntryModeChangeCallback = void Function(TimePickerEntryMode);

1792 1793 1794 1795 1796 1797
/// A material design time picker designed to appear inside a popup dialog.
///
/// Pass this widget to [showDialog]. The value returned by [showDialog] is the
/// selected [TimeOfDay] if the user taps the "OK" button, or null if the user
/// taps the "CANCEL" button. The selected time is reported by calling
/// [Navigator.pop].
1798
class TimePickerDialog extends StatefulWidget {
1799 1800 1801
  /// Creates a material time picker.
  ///
  /// [initialTime] must not be null.
1802
  const TimePickerDialog({
1803 1804
    Key? key,
    required this.initialTime,
1805 1806 1807
    this.cancelText,
    this.confirmText,
    this.helpText,
1808 1809 1810
    this.errorInvalidText,
    this.hourLabelText,
    this.minuteLabelText,
1811
    this.restorationId,
1812
    this.initialEntryMode = TimePickerEntryMode.dial,
1813
    this.onEntryModeChanged,
1814 1815
  }) : assert(initialTime != null),
       super(key: key);
1816

1817
  /// The time initially selected when the dialog is shown.
1818 1819
  final TimeOfDay initialTime;

1820 1821 1822 1823 1824 1825
  /// The entry mode for the picker. Whether it's text input or a dial.
  final TimePickerEntryMode initialEntryMode;

  /// Optionally provide your own text for the cancel button.
  ///
  /// If null, the button uses [MaterialLocalizations.cancelButtonLabel].
1826
  final String? cancelText;
1827 1828 1829 1830

  /// Optionally provide your own text for the confirm button.
  ///
  /// If null, the button uses [MaterialLocalizations.okButtonLabel].
1831
  final String? confirmText;
1832 1833

  /// Optionally provide your own help text to the header of the time picker.
1834
  final String? helpText;
1835

1836 1837 1838 1839 1840 1841 1842 1843 1844
  /// Optionally provide your own validation error text.
  final String? errorInvalidText;

  /// Optionally provide your own hour label text.
  final String? hourLabelText;

  /// Optionally provide your own minute label text.
  final String? minuteLabelText;

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
  /// Restoration ID to save and restore the state of the [TimePickerDialog].
  ///
  /// If it is non-null, the time picker will persist and restore the
  /// dialog's state.
  ///
  /// The state of this widget is persisted in a [RestorationBucket] claimed
  /// from the surrounding [RestorationScope] using the provided restoration ID.
  ///
  /// See also:
  ///
  ///  * [RestorationManager], which explains how state restoration works in
  ///    Flutter.
  final String? restorationId;

1859 1860 1861
  /// Callback called when the selected entry mode is changed.
  final EntryModeChangeCallback? onEntryModeChanged;

1862
  @override
1863
  State<TimePickerDialog> createState() => _TimePickerDialogState();
1864 1865
}

1866 1867 1868 1869 1870 1871 1872 1873 1874
// A restorable [TimePickerEntryMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableTimePickerEntryMode extends RestorableValue<TimePickerEntryMode> {
  _RestorableTimePickerEntryMode(
    TimePickerEntryMode defaultValue,
  ) : _defaultValue = defaultValue;

  final TimePickerEntryMode _defaultValue;
1875

1876
  @override
1877 1878 1879 1880 1881 1882
  TimePickerEntryMode createDefaultValue() => _defaultValue;

  @override
  void didUpdateValue(TimePickerEntryMode? oldValue) {
    assert(debugIsSerializableForRestoration(value.index));
    notifyListeners();
1883 1884
  }

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
  @override
  TimePickerEntryMode fromPrimitives(Object? data) => TimePickerEntryMode.values[data! as int];

  @override
  Object? toPrimitives() => value.index;
}

// A restorable [_RestorableTimePickerEntryMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableTimePickerMode extends RestorableValue<_TimePickerMode> {
  _RestorableTimePickerMode(
    _TimePickerMode defaultValue,
  ) : _defaultValue = defaultValue;

  final _TimePickerMode _defaultValue;

  @override
  _TimePickerMode createDefaultValue() => _defaultValue;

  @override
  void didUpdateValue(_TimePickerMode? oldValue) {
    assert(debugIsSerializableForRestoration(value.index));
    notifyListeners();
  }

  @override
  _TimePickerMode fromPrimitives(Object? data) => _TimePickerMode.values[data! as int];

  @override
  Object? toPrimitives() => value.index;
}

1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
// A restorable [AutovalidateMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableAutovalidateMode extends RestorableValue<AutovalidateMode> {
  _RestorableAutovalidateMode(
      AutovalidateMode defaultValue,
      ) : _defaultValue = defaultValue;

  final AutovalidateMode _defaultValue;

  @override
  AutovalidateMode createDefaultValue() => _defaultValue;

  @override
  void didUpdateValue(AutovalidateMode? oldValue) {
    assert(debugIsSerializableForRestoration(value.index));
    notifyListeners();
  }

  @override
  AutovalidateMode fromPrimitives(Object? data) => AutovalidateMode.values[data! as int];

  @override
  Object? toPrimitives() => value.index;
}

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
// A restorable [_RestorableTimePickerEntryMode] value.
//
// This serializes each entry as a unique `int` value.
//
// This value can be null.
class _RestorableTimePickerModeN extends RestorableValue<_TimePickerMode?> {
  _RestorableTimePickerModeN(
    _TimePickerMode? defaultValue,
  ) : _defaultValue = defaultValue;

  final _TimePickerMode? _defaultValue;

  @override
  _TimePickerMode? createDefaultValue() => _defaultValue;

  @override
  void didUpdateValue(_TimePickerMode? oldValue) {
    assert(debugIsSerializableForRestoration(value?.index));
    notifyListeners();
  }

  @override
  _TimePickerMode fromPrimitives(Object? data) => _TimePickerMode.values[data! as int];

  @override
  Object? toPrimitives() => value?.index;
}

class _TimePickerDialogState extends State<TimePickerDialog> with RestorationMixin {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  late final _RestorableTimePickerEntryMode _entryMode = _RestorableTimePickerEntryMode(widget.initialEntryMode);
  final _RestorableTimePickerMode _mode = _RestorableTimePickerMode(_TimePickerMode.hour);
  final _RestorableTimePickerModeN _lastModeAnnounced = _RestorableTimePickerModeN(null);
1978
  final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode(AutovalidateMode.disabled);
1979 1980 1981 1982
  final RestorableBoolN _autofocusHour = RestorableBoolN(null);
  final RestorableBoolN _autofocusMinute = RestorableBoolN(null);
  final RestorableBool _announcedInitialTime = RestorableBool(false);

1983 1984
  late final VoidCallback _entryModeListener;

1985 1986 1987
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
1988
    localizations = MaterialLocalizations.of(context);
1989 1990 1991 1992
    _announceInitialTimeOnce();
    _announceModeOnce();
  }

1993 1994 1995 1996 1997 1998 1999
  @override
  void initState() {
    super.initState();
    _entryModeListener = () => widget.onEntryModeChanged?.call(_entryMode.value);
    _entryMode.addListener(_entryModeListener);
  }

2000 2001 2002 2003 2004 2005 2006 2007
  @override
  String? get restorationId => widget.restorationId;

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(_entryMode, 'entry_mode');
    registerForRestoration(_mode, 'mode');
    registerForRestoration(_lastModeAnnounced, 'last_mode_announced');
2008
    registerForRestoration(_autovalidateMode, 'autovalidateMode');
2009 2010 2011 2012 2013
    registerForRestoration(_autofocusHour, 'autofocus_hour');
    registerForRestoration(_autofocusMinute, 'autofocus_minute');
    registerForRestoration(_announcedInitialTime, 'announced_initial_time');
    registerForRestoration(_selectedTime, 'selected_time');
  }
2014

2015 2016
  RestorableTimeOfDay get selectedTime => _selectedTime;
  late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.initialTime);
2017

2018 2019
  Timer? _vibrateTimer;
  late MaterialLocalizations localizations;
2020

2021
  void _vibrate() {
2022
    switch (Theme.of(context).platform) {
2023 2024
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
2025 2026
      case TargetPlatform.linux:
      case TargetPlatform.windows:
2027
        _vibrateTimer?.cancel();
2028
        _vibrateTimer = Timer(_kVibrateCommitDelay, () {
2029 2030 2031
          HapticFeedback.vibrate();
          _vibrateTimer = null;
        });
2032 2033
        break;
      case TargetPlatform.iOS:
2034
      case TargetPlatform.macOS:
2035 2036 2037 2038
        break;
    }
  }

2039
  void _handleModeChanged(_TimePickerMode mode) {
2040
    _vibrate();
2041
    setState(() {
2042
      _mode.value = mode;
2043
      _announceModeOnce();
2044 2045 2046
    });
  }

2047 2048
  void _handleEntryModeToggle() {
    setState(() {
2049
      switch (_entryMode.value) {
2050
        case TimePickerEntryMode.dial:
2051
          _autovalidateMode.value = AutovalidateMode.disabled;
2052
          _entryMode.value = TimePickerEntryMode.input;
2053 2054
          break;
        case TimePickerEntryMode.input:
2055
          _formKey.currentState!.save();
2056 2057 2058
          _autofocusHour.value = false;
          _autofocusMinute.value = false;
          _entryMode.value = TimePickerEntryMode.dial;
2059 2060 2061 2062 2063
          break;
      }
    });
  }

2064
  void _announceModeOnce() {
2065
    if (_lastModeAnnounced.value == _mode.value) {
2066 2067 2068 2069
      // Already announced it.
      return;
    }

2070
    switch (_mode.value) {
2071 2072 2073 2074 2075 2076 2077
      case _TimePickerMode.hour:
        _announceToAccessibility(context, localizations.timePickerHourModeAnnouncement);
        break;
      case _TimePickerMode.minute:
        _announceToAccessibility(context, localizations.timePickerMinuteModeAnnouncement);
        break;
    }
2078
    _lastModeAnnounced.value = _mode.value;
2079 2080 2081
  }

  void _announceInitialTimeOnce() {
2082
    if (_announcedInitialTime.value)
2083 2084
      return;

2085
    final MediaQueryData media = MediaQuery.of(context);
2086
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
2087 2088 2089 2090
    _announceToAccessibility(
      context,
      localizations.formatTimeOfDay(widget.initialTime, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
    );
2091
    _announcedInitialTime.value = true;
2092 2093
  }

2094
  void _handleTimeChanged(TimeOfDay value) {
2095
    _vibrate();
2096
    setState(() {
2097
      _selectedTime.value = value;
2098 2099 2100
    });
  }

2101
  void _handleHourDoubleTapped() {
2102
    _autofocusHour.value = true;
2103 2104 2105 2106
    _handleEntryModeToggle();
  }

  void _handleMinuteDoubleTapped() {
2107
    _autofocusMinute.value = true;
2108 2109 2110
    _handleEntryModeToggle();
  }

2111 2112
  void _handleHourSelected() {
    setState(() {
2113
      _mode.value = _TimePickerMode.minute;
2114 2115 2116
    });
  }

2117 2118 2119 2120 2121
  void _handleCancel() {
    Navigator.pop(context);
  }

  void _handleOk() {
2122
    if (_entryMode.value == TimePickerEntryMode.input) {
2123
      final FormState form = _formKey.currentState!;
2124
      if (!form.validate()) {
2125
        setState(() { _autovalidateMode.value = AutovalidateMode.always; });
2126 2127 2128 2129
        return;
      }
      form.save();
    }
2130
    Navigator.pop(context, _selectedTime.value);
2131 2132
  }

2133
  Size _dialogSize(BuildContext context) {
2134
    final Orientation orientation = MediaQuery.of(context).orientation;
2135
    final ThemeData theme = Theme.of(context);
2136 2137 2138
    // Constrain the textScaleFactor to prevent layout issues. Since only some
    // parts of the time picker scale up with textScaleFactor, we cap the factor
    // to 1.1 as that provides enough space to reasonably fit all the content.
2139
    final double textScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 1.1);
2140

2141 2142
    final double timePickerWidth;
    final double timePickerHeight;
2143
    switch (_entryMode.value) {
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
      case TimePickerEntryMode.dial:
        switch (orientation) {
          case Orientation.portrait:
            timePickerWidth = _kTimePickerWidthPortrait;
            timePickerHeight = theme.materialTapTargetSize == MaterialTapTargetSize.padded
                ? _kTimePickerHeightPortrait
                : _kTimePickerHeightPortraitCollapsed;
            break;
          case Orientation.landscape:
            timePickerWidth = _kTimePickerWidthLandscape * textScaleFactor;
            timePickerHeight = theme.materialTapTargetSize == MaterialTapTargetSize.padded
                ? _kTimePickerHeightLandscape
                : _kTimePickerHeightLandscapeCollapsed;
            break;
        }
        break;
      case TimePickerEntryMode.input:
        timePickerWidth = _kTimePickerWidthPortrait;
        timePickerHeight = _kTimePickerHeightInput;
        break;
    }
    return Size(timePickerWidth, timePickerHeight * textScaleFactor);
  }

2168 2169
  @override
  Widget build(BuildContext context) {
2170
    assert(debugCheckHasMediaQuery(context));
2171
    final MediaQueryData media = MediaQuery.of(context);
2172
    final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
2173
    final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
2174
    final ThemeData theme = Theme.of(context);
2175 2176
    final ShapeBorder shape = TimePickerTheme.of(context).shape ?? _kDefaultShape;
    final Orientation orientation = media.orientation;
Yegor's avatar
Yegor committed
2177

2178
    final Widget actions = Row(
2179
      children: <Widget>[
2180 2181 2182 2183 2184 2185
        const SizedBox(width: 10.0),
        IconButton(
          color: TimePickerTheme.of(context).entryModeIconColor ?? theme.colorScheme.onSurface.withOpacity(
            theme.colorScheme.brightness == Brightness.dark ? 1.0 : 0.6,
          ),
          onPressed: _handleEntryModeToggle,
2186 2187
          icon: Icon(_entryMode.value == TimePickerEntryMode.dial ? Icons.keyboard : Icons.access_time),
          tooltip: _entryMode.value == TimePickerEntryMode.dial
2188 2189
              ? MaterialLocalizations.of(context).inputTimeModeButtonLabel
              : MaterialLocalizations.of(context).dialModeButtonLabel,
2190
        ),
2191
        Expanded(
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
          child: Container(
            alignment: AlignmentDirectional.centerEnd,
            constraints: const BoxConstraints(minHeight: 52.0),
            padding: const EdgeInsets.symmetric(horizontal: 8),
            child: OverflowBar(
              spacing: 8,
              overflowAlignment: OverflowBarAlignment.end,
              children: <Widget>[
                TextButton(
                  onPressed: _handleCancel,
                  child: Text(widget.cancelText ?? localizations.cancelButtonLabel),
                ),
                TextButton(
                  onPressed: _handleOk,
                  child: Text(widget.confirmText ?? localizations.okButtonLabel),
                ),
              ],
            ),
2210
          ),
2211 2212
        ),
      ],
2213 2214
    );

2215
    final Widget picker;
2216
    switch (_entryMode.value) {
2217 2218 2219 2220 2221 2222 2223
      case TimePickerEntryMode.dial:
        final Widget dial = Padding(
          padding: orientation == Orientation.portrait ? const EdgeInsets.symmetric(horizontal: 36, vertical: 24) : const EdgeInsets.all(24),
          child: ExcludeSemantics(
            child: AspectRatio(
              aspectRatio: 1.0,
              child: _Dial(
2224
                mode: _mode.value,
2225
                use24HourDials: use24HourDials,
2226
                selectedTime: _selectedTime.value,
2227 2228 2229 2230 2231 2232 2233 2234
                onChanged: _handleTimeChanged,
                onHourSelected: _handleHourSelected,
              ),
            ),
          ),
        );

        final Widget header = _TimePickerHeader(
2235 2236
          selectedTime: _selectedTime.value,
          mode: _mode.value,
2237 2238 2239
          orientation: orientation,
          onModeChanged: _handleModeChanged,
          onChanged: _handleTimeChanged,
2240 2241
          onHourDoubleTapped: _handleHourDoubleTapped,
          onMinuteDoubleTapped: _handleMinuteDoubleTapped,
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
          use24HourDials: use24HourDials,
          helpText: widget.helpText,
        );

        switch (orientation) {
          case Orientation.portrait:
            picker = Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                header,
                Expanded(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      // Dial grows and shrinks with the available space.
                      Expanded(child: dial),
                      actions,
                    ],
                  ),
                ),
              ],
            );
            break;
          case Orientation.landscape:
            picker = Column(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      header,
                      Expanded(child: dial),
                    ],
                  ),
                ),
                actions,
              ],
            );
            break;
        }
        break;
      case TimePickerEntryMode.input:
        picker = Form(
          key: _formKey,
2286
          autovalidateMode: _autovalidateMode.value,
2287
          child: SingleChildScrollView(
2288
            restorationId: 'time_picker_scroll_view',
2289
            child: Column(
2290 2291
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
2292
                _TimePickerInput(
2293
                  initialSelectedTime: _selectedTime.value,
2294
                  helpText: widget.helpText,
2295 2296 2297
                  errorInvalidText: widget.errorInvalidText,
                  hourLabelText: widget.hourLabelText,
                  minuteLabelText: widget.minuteLabelText,
2298 2299
                  autofocusHour: _autofocusHour.value,
                  autofocusMinute: _autofocusMinute.value,
2300
                  onChanged: _handleTimeChanged,
2301
                  restorationId: 'time_picker_input',
2302
                ),
2303 2304 2305
                actions,
              ],
            ),
2306 2307 2308 2309
          ),
        );
        break;
    }
2310

2311 2312 2313 2314 2315 2316
    final Size dialogSize = _dialogSize(context);
    return Dialog(
      shape: shape,
      backgroundColor: TimePickerTheme.of(context).backgroundColor ?? theme.colorScheme.surface,
      insetPadding: EdgeInsets.symmetric(
        horizontal: 16.0,
2317
        vertical: _entryMode.value == TimePickerEntryMode.input ? 0.0 : 24.0,
2318 2319 2320 2321 2322 2323 2324
      ),
      child: AnimatedContainer(
        width: dialogSize.width,
        height: dialogSize.height,
        duration: _kDialogSizeAnimationDuration,
        curve: Curves.easeIn,
        child: picker,
2325 2326
      ),
    );
2327
  }
2328 2329 2330 2331 2332

  @override
  void dispose() {
    _vibrateTimer?.cancel();
    _vibrateTimer = null;
2333
    _entryMode.removeListener(_entryModeListener);
2334 2335
    super.dispose();
  }
2336 2337 2338 2339 2340
}

/// Shows a dialog containing a material design time picker.
///
/// The returned Future resolves to the time selected by the user when the user
2341
/// closes the dialog. If the user cancels the dialog, null is returned.
2342
///
2343
/// {@tool snippet}
2344
/// Show a dialog with [initialTime] equal to the current time.
Ian Hickson's avatar
Ian Hickson committed
2345
///
2346
/// ```dart
2347
/// Future<TimeOfDay?> selectedTime = showTimePicker(
2348
///   initialTime: TimeOfDay.now(),
Ian Hickson's avatar
Ian Hickson committed
2349
///   context: context,
2350 2351
/// );
/// ```
2352
/// {@end-tool}
2353
///
2354 2355
/// The [context], [useRootNavigator] and [routeSettings] arguments are passed to
/// [showDialog], the documentation for which discusses how it is used.
Ian Hickson's avatar
Ian Hickson committed
2356
///
2357 2358 2359 2360
/// The [builder] parameter can be used to wrap the dialog widget
/// to add inherited widgets like [Localizations.override],
/// [Directionality], or [MediaQuery].
///
2361
/// The `initialEntryMode` parameter can be used to
2362 2363 2364
/// determine the initial time entry selection of the picker (either a clock
/// dial or text input).
///
2365 2366 2367
/// Optional strings for the [helpText], [cancelText], [errorInvalidText],
/// [hourLabelText], [minuteLabelText] and [confirmText] can be provided to
/// override the default values.
2368
///
2369 2370 2371 2372
/// By default, the time picker gets its colors from the overall theme's
/// [ColorScheme]. The time picker can be further customized by providing a
/// [TimePickerThemeData] to the overall theme.
///
2373
/// {@tool snippet}
2374 2375 2376
/// Show a dialog with the text direction overridden to be [TextDirection.rtl].
///
/// ```dart
2377
/// Future<TimeOfDay?> selectedTimeRTL = showTimePicker(
2378 2379
///   context: context,
///   initialTime: TimeOfDay.now(),
2380
///   builder: (BuildContext context, Widget? child) {
2381 2382
///     return Directionality(
///       textDirection: TextDirection.rtl,
2383
///       child: child!,
2384 2385 2386 2387 2388 2389
///     );
///   },
/// );
/// ```
/// {@end-tool}
///
2390
/// {@tool snippet}
2391 2392 2393
/// Show a dialog with time unconditionally displayed in 24 hour format.
///
/// ```dart
2394
/// Future<TimeOfDay?> selectedTime24Hour = showTimePicker(
2395
///   context: context,
2396
///   initialTime: const TimeOfDay(hour: 10, minute: 47),
2397
///   builder: (BuildContext context, Widget? child) {
2398 2399
///     return MediaQuery(
///       data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
2400
///       child: child!,
2401 2402 2403 2404 2405 2406
///     );
///   },
/// );
/// ```
/// {@end-tool}
///
2407 2408
/// See also:
///
2409 2410
///  * [showDatePicker], which shows a dialog that contains a material design
///    date picker.
2411 2412
///  * [TimePickerThemeData], which allows you to customize the colors,
///    typography, and shape of the time picker.
2413
Future<TimeOfDay?> showTimePicker({
2414 2415 2416
  required BuildContext context,
  required TimeOfDay initialTime,
  TransitionBuilder? builder,
2417
  bool useRootNavigator = true,
2418
  TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial,
2419 2420 2421
  String? cancelText,
  String? confirmText,
  String? helpText,
2422 2423 2424
  String? errorInvalidText,
  String? hourLabelText,
  String? minuteLabelText,
2425
  RouteSettings? routeSettings,
2426
  EntryModeChangeCallback? onEntryModeChanged,
2427
}) async {
2428
  assert(context != null);
2429
  assert(initialTime != null);
2430
  assert(useRootNavigator != null);
2431
  assert(initialEntryMode != null);
2432
  assert(debugCheckHasMaterialLocalizations(context));
2433

2434
  final Widget dialog = TimePickerDialog(
2435 2436 2437 2438 2439
    initialTime: initialTime,
    initialEntryMode: initialEntryMode,
    cancelText: cancelText,
    confirmText: confirmText,
    helpText: helpText,
2440 2441 2442
    errorInvalidText: errorInvalidText,
    hourLabelText: hourLabelText,
    minuteLabelText: minuteLabelText,
2443
    onEntryModeChanged: onEntryModeChanged,
2444
  );
2445
  return showDialog<TimeOfDay>(
2446
    context: context,
2447
    useRootNavigator: useRootNavigator,
2448 2449 2450
    builder: (BuildContext context) {
      return builder == null ? dialog : builder(context, dialog);
    },
2451
    routeSettings: routeSettings,
2452
  );
2453
}
2454 2455

void _announceToAccessibility(BuildContext context, String message) {
2456
  SemanticsService.announce(message, Directionality.of(context));
2457
}