time_picker.dart 67.4 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 6
// @dart = 2.8

7
import 'dart:async';
8 9
import 'dart:math' as math;

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

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

39 40 41
// Examples can assume:
// BuildContext context;

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

47 48
enum _TimePickerMode { hour, minute }

49 50
const double _kTimePickerHeaderLandscapeWidth = 264.0;
const double _kTimePickerHeaderControlHeight = 80.0;
51

52
const double _kTimePickerWidthPortrait = 328.0;
53
const double _kTimePickerWidthLandscape = 528.0;
54

55
const double _kTimePickerHeightInput = 226.0;
56 57 58 59 60
const double _kTimePickerHeightPortrait = 496.0;
const double _kTimePickerHeightLandscape = 316.0;

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

62 63
const BorderRadius _kDefaultBorderRadius = BorderRadius.all(Radius.circular(4.0));
const ShapeBorder _kDefaultShape = RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius);
Yegor's avatar
Yegor committed
64

65 66 67 68 69 70 71 72 73 74 75 76
/// 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
77 78 79 80 81 82 83 84 85 86
}

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

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

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

115 116
  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
117
  final Orientation orientation;
118 119 120 121
  final ValueChanged<_TimePickerMode> onModeChanged;
  final ValueChanged<TimeOfDay> onChanged;
  final bool use24HourDials;
  final String helpText;
Yegor's avatar
Yegor committed
122

123 124 125
  void _handleChangeMode(_TimePickerMode value) {
    if (value != mode)
      onModeChanged(value);
Yegor's avatar
Yegor committed
126 127 128 129
  }

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

    final _TimePickerFragmentContext fragmentContext = _TimePickerFragmentContext(
      selectedTime: selectedTime,
      mode: mode,
      onTimeChange: onChanged,
      onModeChange: _handleChangeMode,
      use24HourDials: use24HourDials,
Yegor's avatar
Yegor committed
142
    );
143

144 145 146
    EdgeInsets padding;
    double width;
    Widget controls;
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    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),
            Container(
              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),
                  ],
                  Expanded(child: _HourControl(fragmentContext: fragmentContext)),
                  _StringFragment(timeOfDayFormat: timeOfDayFormat),
                  Expanded(child: _MinuteControl(fragmentContext: fragmentContext)),
                  if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                    const SizedBox(width: 12.0),
                    _DayPeriodControl(
                      selectedTime: selectedTime,
                      orientation: orientation,
                      onChanged: onChanged,
                    ),
                  ]
                ],
179 180
              ),
            ),
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
          ],
        );
        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,
                ),
              Container(
                height: kMinInteractiveDimension * 2,
                child: Row(
                  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,
                ),
            ],
214
          ),
215 216 217 218 219 220 221 222 223 224 225 226
        );
        break;
    }

    return Container(
      width: width,
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const SizedBox(height: 16.0),
          Text(
227
            helpText ?? MaterialLocalizations.of(context).timePickerDialHelpText,
228 229 230 231
            style: TimePickerTheme.of(context).helpTextStyle ?? themeData.textTheme.overline,
          ),
          controls,
        ],
232 233
      ),
    );
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  }
}

class _HourMinuteControl extends StatelessWidget {
  const _HourMinuteControl({
    @required this.text,
    @required this.onTap,
    @required this.isSelected,
  }) : assert(text != null),
       assert(onTap != null),
       assert(isSelected != null);

  final String text;
  final GestureTapCallback onTap;
  final bool isSelected;
249

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  @override
  Widget build(BuildContext context) {
    final ThemeData themeData = Theme.of(context);
    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);
        });
    final TextStyle style = timePickerTheme.hourMinuteTextStyle ?? themeData.textTheme.headline2;
    final ShapeBorder shape = timePickerTheme.hourMinuteShape ?? _kDefaultShape;

    final Set<MaterialState> states = isSelected ? <MaterialState>{MaterialState.selected} : <MaterialState>{};
    return Container(
      height: _kTimePickerHeaderControlHeight,
273
      child: Material(
274 275 276
        color: MaterialStateProperty.resolveAs(backgroundColor, states),
        clipBehavior: Clip.antiAlias,
        shape: shape,
277
        child: InkWell(
278 279 280 281 282 283
          onTap: onTap,
          child: Center(
            child: Text(
              text,
              style: style.copyWith(color: MaterialStateProperty.resolveAs(textColor, states)),
              textScaleFactor: 1.0,
284
            ),
285 286
          ),
        ),
287
      ),
Yegor's avatar
Yegor committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    );
  }
}
/// Displays the hour fragment.
///
/// When tapped changes time picker dial mode to [_TimePickerMode.hour].
class _HourControl extends StatelessWidget {
  const _HourControl({
    @required this.fragmentContext,
  });

  final _TimePickerFragmentContext fragmentContext;

  @override
  Widget build(BuildContext context) {
303
    assert(debugCheckHasMediaQuery(context));
304
    final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat;
305
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
306 307
    final String formattedHour = localizations.formatHour(
      fragmentContext.selectedTime,
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
      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,
336
    );
Yegor's avatar
Yegor committed
337

338 339 340 341 342 343 344 345 346 347 348 349
    return Semantics(
      hint: localizations.timePickerHourModeAnnouncement,
      value: formattedHour,
      excludeSemantics: true,
      increasedValue: formattedNextHour,
      onIncrease: () {
        fragmentContext.onTimeChange(nextHour);
      },
      decreasedValue: formattedPreviousHour,
      onDecrease: () {
        fragmentContext.onTimeChange(previousHour);
      },
350 351 352 353
      child: _HourMinuteControl(
        isSelected: fragmentContext.mode == _TimePickerMode.hour,
        text: formattedHour,
        onTap: Feedback.wrapForTap(() => fragmentContext.onModeChange(_TimePickerMode.hour), context),
354
      ),
Yegor's avatar
Yegor committed
355 356 357 358 359 360 361
    );
  }
}

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

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
  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';
    }
    return '';
  }
Yegor's avatar
Yegor committed
381 382 383

  @override
  Widget build(BuildContext context) {
384 385 386 387 388
    final ThemeData theme = Theme.of(context);
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
    final TextStyle hourMinuteStyle = timePickerTheme.hourMinuteTextStyle ?? theme.textTheme.headline2;
    final Color textColor = timePickerTheme.hourMinuteTextColor ?? theme.colorScheme.onSurface;

389
    return ExcludeSemantics(
390 391 392 393 394 395 396 397 398 399
      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,
          ),
        ),
      ),
400
    );
Yegor's avatar
Yegor committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
  }
}

/// Displays the minute fragment.
///
/// When tapped changes time picker dial mode to [_TimePickerMode.minute].
class _MinuteControl extends StatelessWidget {
  const _MinuteControl({
    @required this.fragmentContext,
  });

  final _TimePickerFragmentContext fragmentContext;

  @override
  Widget build(BuildContext context) {
416
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
417 418 419 420 421 422 423 424 425
    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
426

427 428 429 430 431 432 433 434 435 436 437 438
    return Semantics(
      excludeSemantics: true,
      hint: localizations.timePickerMinuteModeAnnouncement,
      value: formattedMinute,
      increasedValue: formattedNextMinute,
      onIncrease: () {
        fragmentContext.onTimeChange(nextMinute);
      },
      decreasedValue: formattedPreviousMinute,
      onDecrease: () {
        fragmentContext.onTimeChange(previousMinute);
      },
439 440 441 442
      child: _HourMinuteControl(
        isSelected: fragmentContext.mode == _TimePickerMode.minute,
        text: formattedMinute,
        onTap: Feedback.wrapForTap(() => fragmentContext.onModeChange(_TimePickerMode.minute), context),
443
      ),
Yegor's avatar
Yegor committed
444 445 446 447 448
    );
  }
}


449 450 451 452 453 454 455 456
/// Displays the am/pm fragment and provides controls for switching between am
/// and pm.
class _DayPeriodControl extends StatelessWidget {
  const _DayPeriodControl({
    @required this.selectedTime,
    @required this.onChanged,
    @required this.orientation,
  });
Yegor's avatar
Yegor committed
457

458 459 460
  final TimeOfDay selectedTime;
  final Orientation orientation;
  final ValueChanged<TimeOfDay> onChanged;
Yegor's avatar
Yegor committed
461

462 463 464 465
  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
466 467
  }

468 469 470 471 472 473 474 475 476 477
  void _setAm(BuildContext context) {
    if (selectedTime.period == DayPeriod.am) {
      return;
    }
    switch (Theme.of(context).platform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        _announceToAccessibility(context, MaterialLocalizations.of(context).anteMeridiemAbbreviation);
Yegor's avatar
Yegor committed
478
        break;
479 480
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
Yegor's avatar
Yegor committed
481 482
        break;
    }
483 484 485 486 487 488
    _togglePeriod();
  }

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

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  @override
  Widget build(BuildContext context) {
    final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(context);
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
    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>{};
    final TextStyle textStyle = timePickerTheme.dayPeriodTextStyle ?? Theme.of(context).textTheme.subtitle1;
    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,
    );
546

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

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    final Widget amButton = Material(
      color: MaterialStateProperty.resolveAs(backgroundColor, amStates),
      child: InkWell(
        onTap: Feedback.wrapForTap(() => _setAm(context), context),
        child: Semantics(
          selected: amSelected,
          child: Center(
            child: Text(
              materialLocalizations.anteMeridiemAbbreviation,
              style: amStyle,
              textScaleFactor: buttonTextScaleFactor,
            ),
          ),
        ),
      ),
    );
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    final Widget pmButton = Material(
      color: MaterialStateProperty.resolveAs(backgroundColor, pmStates),
      child: InkWell(
        onTap: Feedback.wrapForTap(() => _setPm(context), context),
        child: Semantics(
          selected: pmSelected,
          child: Center(
            child: Text(
              materialLocalizations.postMeridiemAbbreviation,
              style: pmStyle,
              textScaleFactor: buttonTextScaleFactor,
            ),
          ),
        ),
      ),
    );
582

583
    Widget result;
584 585
    switch (orientation) {
      case Orientation.portrait:
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        const double width = 52.0;
        result = _DayPeriodInputPadding(
          minSize: const Size(width, kMinInteractiveDimension * 2),
          orientation: orientation,
          child: Container(
            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
612 613
        break;
      case Orientation.landscape:
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        result = _DayPeriodInputPadding(
          minSize: const Size(0.0, kMinInteractiveDimension),
          orientation: orientation,
          child: Container(
            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
638 639
        break;
    }
640
    return result;
Yegor's avatar
Yegor committed
641
  }
642
}
643

644 645 646 647 648 649 650 651
/// A widget to pad the area around the [_DayPeriodControl]'s inner [Material].
class _DayPeriodInputPadding extends SingleChildRenderObjectWidget {
  const _DayPeriodInputPadding({
    Key key,
    Widget child,
    this.minSize,
    this.orientation,
  }) : super(key: key, child: child);
652

653 654
  final Size minSize;
  final Orientation orientation;
655

656 657 658
  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderInputPadding(minSize, orientation);
Yegor's avatar
Yegor committed
659
  }
660

661 662 663 664 665
  @override
  void updateRenderObject(BuildContext context, covariant _RenderInputPadding renderObject) {
    renderObject.minSize = minSize;
  }
}
666

667 668
class _RenderInputPadding extends RenderShiftedBox {
  _RenderInputPadding(this._minSize, this.orientation, [RenderBox child]) : super(child);
669

670 671 672 673 674 675 676 677 678
  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
679
  }
680

681 682 683 684
  @override
  double computeMinIntrinsicWidth(double height) {
    if (child != null) {
      return math.max(child.getMinIntrinsicWidth(height), minSize.width);
Yegor's avatar
Yegor committed
685
    }
686 687
    return 0.0;
  }
688

689 690 691 692
  @override
  double computeMinIntrinsicHeight(double width) {
    if (child != null) {
      return math.max(child.getMinIntrinsicHeight(width), minSize.height);
Yegor's avatar
Yegor committed
693
    }
694
    return 0.0;
Yegor's avatar
Yegor committed
695
  }
696

697 698 699 700
  @override
  double computeMaxIntrinsicWidth(double height) {
    if (child != null) {
      return math.max(child.getMaxIntrinsicWidth(height), minSize.width);
701
    }
702
    return 0.0;
703 704 705
  }

  @override
706 707 708 709 710
  double computeMaxIntrinsicHeight(double width) {
    if (child != null) {
      return math.max(child.getMaxIntrinsicHeight(width), minSize.height);
    }
    return 0.0;
711 712
  }

713 714 715 716 717 718 719 720 721 722 723
  @override
  void performLayout() {
    if (child != null) {
      child.layout(constraints, parentUsesSize: true);
      final double width = math.max(child.size.width, minSize.width);
      final double height = math.max(child.size.height, minSize.height);
      size = constraints.constrain(Size(width, height));
      final BoxParentData childParentData = child.parentData as BoxParentData;
      childParentData.offset = Alignment.center.alongOffset(size - child.size as Offset);
    } else {
      size = Size.zero;
724 725 726
    }
  }

727
  @override
728 729 730 731
  bool hitTest(BoxHitTestResult result, { Offset position }) {
    if (super.hitTest(result, position: position)) {
      return true;
    }
Yegor's avatar
Yegor committed
732

733 734 735 736 737 738
    if (position.dx < 0.0 ||
        position.dx > math.max(child.size.width, minSize.width) ||
        position.dy < 0.0 ||
        position.dy > math.max(child.size.height, minSize.height)) {
      return false;
    }
Yegor's avatar
Yegor committed
739

740
    Offset newPosition = child.size.center(Offset.zero);
Yegor's avatar
Yegor committed
741 742
    switch (orientation) {
      case Orientation.portrait:
743 744 745 746 747
        if (position.dy > newPosition.dy) {
          newPosition += const Offset(0.0, 1.0);
        } else {
          newPosition += const Offset(0.0, -1.0);
        }
748
        break;
Yegor's avatar
Yegor committed
749
      case Orientation.landscape:
750 751 752 753 754
        if (position.dx > newPosition.dx) {
          newPosition += const Offset(1.0, 0.0);
        } else {
          newPosition += const Offset(-1.0, 0.0);
        }
755 756
        break;
    }
757 758


759 760 761 762 763 764 765
    return result.addWithRawTransform(
      transform: MatrixUtils.forceToPoint(newPosition),
      position: newPosition,
      hitTest: (BoxHitTestResult result, Offset position) {
        assert(position == newPosition);
        return child.hitTest(result, position: newPosition);
      },
766
    );
767 768
  }
}
769

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
class _TappableLabel {
  _TappableLabel({
    @required this.value,
    @required this.painter,
    @required this.onTap,
  });

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

787
class _DialPainter extends CustomPainter {
788
  _DialPainter({
789 790
    @required this.primaryLabels,
    @required this.secondaryLabels,
Yegor's avatar
Yegor committed
791 792
    @required this.backgroundColor,
    @required this.accentColor,
793
    @required this.dotColor,
Yegor's avatar
Yegor committed
794
    @required this.theta,
795 796
    @required this.textDirection,
    @required this.selectedValue,
797
  }) : super(repaint: PaintingBinding.instance.systemFonts);
798

799 800
  final List<_TappableLabel> primaryLabels;
  final List<_TappableLabel> secondaryLabels;
801 802
  final Color backgroundColor;
  final Color accentColor;
803
  final Color dotColor;
804
  final double theta;
805 806
  final TextDirection textDirection;
  final int selectedValue;
807

808 809
  static const double _labelPadding = 28.0;

810
  @override
811
  void paint(Canvas canvas, Size size) {
812
    final double radius = size.shortestSide / 2.0;
813
    final Offset center = Offset(size.width / 2.0, size.height / 2.0);
814
    final Offset centerPoint = center;
815
    canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor);
816

817 818 819
    final double labelRadius = radius - _labelPadding;
    Offset getOffsetForTheta(double theta) {
      return center + Offset(labelRadius * math.cos(theta), -labelRadius * math.sin(theta));
820 821
    }

822
    void paintLabels(List<_TappableLabel> labels) {
Yegor's avatar
Yegor committed
823 824
      if (labels == null)
        return;
825
      final double labelThetaIncrement = -_kTwoPi / labels.length;
826
      double labelTheta = math.pi / 2.0;
827

828
      for (final _TappableLabel label in labels) {
829 830 831
        final TextPainter labelPainter = label.painter;
        final Offset labelOffset = Offset(-labelPainter.width / 2.0, -labelPainter.height / 2.0);
        labelPainter.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset);
832 833 834 835
        labelTheta += labelThetaIncrement;
      }
    }

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    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);
    }
855

856 857 858 859 860 861 862 863
    final Rect focusedRect = Rect.fromCircle(
      center: focusedPoint, radius: focusedRadius,
    );
    canvas
      ..save()
      ..clipPath(Path()..addOval(focusedRect));
    paintLabels(secondaryLabels);
    canvas.restore();
864 865
  }

866
  @override
867
  bool shouldRepaint(_DialPainter oldPainter) {
868 869
    return oldPainter.primaryLabels != primaryLabels
        || oldPainter.secondaryLabels != secondaryLabels
870 871
        || oldPainter.backgroundColor != backgroundColor
        || oldPainter.accentColor != accentColor
872
        || oldPainter.theta != theta;
873 874 875
  }
}

876
class _Dial extends StatefulWidget {
877
  const _Dial({
878 879
    @required this.selectedTime,
    @required this.mode,
880
    @required this.use24HourDials,
881
    @required this.onChanged,
882 883 884 885
    @required this.onHourSelected,
  }) : assert(selectedTime != null),
       assert(mode != null),
       assert(use24HourDials != null);
886 887 888

  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
889
  final bool use24HourDials;
890
  final ValueChanged<TimeOfDay> onChanged;
891
  final VoidCallback onHourSelected;
892

893
  @override
894
  _DialState createState() => _DialState();
895 896
}

897
class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
898
  @override
899 900
  void initState() {
    super.initState();
901
    _thetaController = AnimationController(
902 903 904
      duration: _kDialAnimateDuration,
      vsync: this,
    );
905
    _thetaTween = Tween<double>(begin: _getThetaForTime(widget.selectedTime));
906
    _theta = _thetaController
907
      .drive(CurveTween(curve: standardEasing))
908 909
      .drive(_thetaTween)
      ..addListener(() => setState(() { /* _theta.value has changed */ }));
910 911
  }

912 913 914 915 916 917 918 919 920 921 922 923 924
  ThemeData themeData;
  MaterialLocalizations localizations;
  MediaQueryData media;

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

925
  @override
926
  void didUpdateWidget(_Dial oldWidget) {
927
    super.didUpdateWidget(oldWidget);
928
    if (widget.mode != oldWidget.mode || widget.selectedTime != oldWidget.selectedTime) {
Yegor's avatar
Yegor committed
929 930 931
      if (!_dragging)
        _animateTo(_getThetaForTime(widget.selectedTime));
    }
932 933
  }

934 935 936 937 938 939
  @override
  void dispose() {
    _thetaController.dispose();
    super.dispose();
  }

940
  Tween<double> _thetaTween;
941
  Animation<double> _theta;
942
  AnimationController _thetaController;
Adam Barth's avatar
Adam Barth committed
943 944 945 946 947 948 949
  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) {
950
    final double currentTheta = _theta.value;
Adam Barth's avatar
Adam Barth committed
951 952
    double beginTheta = _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi);
    beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi);
953 954 955 956 957 958
    _thetaTween
      ..begin = beginTheta
      ..end = targetTheta;
    _thetaController
      ..value = 0.0
      ..forward();
959 960 961
  }

  double _getThetaForTime(TimeOfDay time) {
962
    final int hoursFactor = widget.use24HourDials ? TimeOfDay.hoursPerDay : TimeOfDay.hoursPerPeriod;
963
    final double fraction = widget.mode == _TimePickerMode.hour
964
      ? (time.hour / hoursFactor) % hoursFactor
965
      : (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour;
966
    return (math.pi / 2.0 - fraction * _kTwoPi) % _kTwoPi;
967 968
  }

969
  TimeOfDay _getTimeForTheta(double theta, {bool roundMinutes = false}) {
970
    final double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0;
971
    if (widget.mode == _TimePickerMode.hour) {
972
      int newHour;
973
      if (widget.use24HourDials) {
974
        newHour = (fraction * TimeOfDay.hoursPerDay).round() % TimeOfDay.hoursPerDay;
Yegor's avatar
Yegor committed
975
      } else {
976
        newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % TimeOfDay.hoursPerPeriod;
Yegor's avatar
Yegor committed
977 978 979
        newHour = newHour + widget.selectedTime.periodOffset;
      }
      return widget.selectedTime.replacing(hour: newHour);
980
    } else {
981 982 983 984 985 986
      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);
987 988 989
    }
  }

990 991
  TimeOfDay _notifyOnChangedIfNeeded({ bool roundMinutes = false }) {
    final TimeOfDay current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes);
992 993
    if (widget.onChanged == null)
      return current;
994 995
    if (current != widget.selectedTime)
      widget.onChanged(current);
996
    return current;
997 998
  }

999
  void _updateThetaForPan({ bool roundMinutes = false }) {
1000
    setState(() {
Hans Muller's avatar
Hans Muller committed
1001
      final Offset offset = _position - _center;
1002 1003 1004 1005
      double angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2.0) % _kTwoPi;
      if (roundMinutes) {
        angle = _getThetaForTime(_getTimeForTheta(angle, roundMinutes: roundMinutes));
      }
1006
      _thetaTween
Hans Muller's avatar
Hans Muller committed
1007 1008
        ..begin = angle
        ..end = angle; // The controller doesn't animate during the pan gesture.
1009 1010 1011
    });
  }

1012 1013
  Offset _position;
  Offset _center;
1014

1015
  void _handlePanStart(DragStartDetails details) {
Adam Barth's avatar
Adam Barth committed
1016 1017
    assert(!_dragging);
    _dragging = true;
1018
    final RenderBox box = context.findRenderObject() as RenderBox;
1019
    _position = box.globalToLocal(details.globalPosition);
1020
    _center = box.size.center(Offset.zero);
1021 1022 1023 1024
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

1025 1026
  void _handlePanUpdate(DragUpdateDetails details) {
    _position += details.delta;
1027 1028 1029 1030
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

1031
  void _handlePanEnd(DragEndDetails details) {
Adam Barth's avatar
Adam Barth committed
1032 1033
    assert(_dragging);
    _dragging = false;
1034 1035
    _position = null;
    _center = null;
1036
    _animateTo(_getThetaForTime(widget.selectedTime));
1037 1038 1039 1040 1041
    if (widget.mode == _TimePickerMode.hour) {
      if (widget.onHourSelected != null) {
        widget.onHourSelected();
      }
    }
1042 1043
  }

1044
  void _handleTapUp(TapUpDetails details) {
1045
    final RenderBox box = context.findRenderObject() as RenderBox;
1046 1047
    _position = box.globalToLocal(details.globalPosition);
    _center = box.size.center(Offset.zero);
1048 1049
    _updateThetaForPan(roundMinutes: true);
    final TimeOfDay newTime = _notifyOnChangedIfNeeded(roundMinutes: true);
1050 1051 1052 1053 1054 1055
    if (widget.mode == _TimePickerMode.hour) {
      if (widget.use24HourDials) {
        _announceToAccessibility(context, localizations.formatDecimal(newTime.hour));
      } else {
        _announceToAccessibility(context, localizations.formatDecimal(newTime.hourOfPeriod));
      }
1056 1057 1058
      if (widget.onHourSelected != null) {
        widget.onHourSelected();
      }
1059 1060 1061
    } else {
      _announceToAccessibility(context, localizations.formatDecimal(newTime.minute));
    }
1062
    _animateTo(_getThetaForTime(_getTimeForTheta(_theta.value, roundMinutes: true)));
1063 1064 1065 1066 1067 1068 1069 1070 1071
    _dragging = false;
    _position = null;
    _center = null;
  }

  void _selectHour(int hour) {
    _announceToAccessibility(context, localizations.formatDecimal(hour));
    TimeOfDay time;
    if (widget.mode == _TimePickerMode.hour && widget.use24HourDials) {
1072
      time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute);
1073 1074
    } else {
      if (widget.selectedTime.period == DayPeriod.am) {
1075
        time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute);
1076
      } else {
1077
        time = TimeOfDay(hour: hour + TimeOfDay.hoursPerPeriod, minute: widget.selectedTime.minute);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
      }
    }
    final double angle = _getThetaForTime(time);
    _thetaTween
      ..begin = angle
      ..end = angle;
    _notifyOnChangedIfNeeded();
  }

  void _selectMinute(int minute) {
    _announceToAccessibility(context, localizations.formatDecimal(minute));
1089
    final TimeOfDay time = TimeOfDay(
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
      hour: widget.selectedTime.hour,
      minute: minute,
    );
    final double angle = _getThetaForTime(time);
    _thetaTween
      ..begin = angle
      ..end = angle;
    _notifyOnChangedIfNeeded();
  }

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  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),
1113 1114
  ];

1115
  static const List<TimeOfDay> _twentyFourHours = <TimeOfDay>[
1116
    TimeOfDay(hour: 0, minute: 0),
1117 1118 1119 1120 1121 1122
    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),
1123 1124 1125 1126 1127
    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),
1128 1129
  ];

1130 1131
  _TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, int value, String label, VoidCallback onTap) {
    final TextStyle style = textTheme.subtitle1.copyWith(color: color);
1132
    final double labelScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 2.0);
1133
    return _TappableLabel(
1134
      value: value,
1135 1136
      painter: TextPainter(
        text: TextSpan(style: style, text: label),
1137
        textDirection: TextDirection.ltr,
1138
        textScaleFactor: labelScaleFactor,
1139 1140 1141
      )..layout(),
      onTap: onTap,
    );
1142 1143
  }

1144
  List<_TappableLabel> _build24HourRing(TextTheme textTheme, Color color) => <_TappableLabel>[
1145
    for (final TimeOfDay timeOfDay in _twentyFourHours)
1146
      _buildTappableLabel(
1147
        textTheme,
1148
        color,
1149 1150 1151 1152 1153
        timeOfDay.hour,
        localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
        () {
          _selectHour(timeOfDay.hour);
        },
1154 1155
      ),
  ];
1156

1157
  List<_TappableLabel> _build12HourRing(TextTheme textTheme, Color color) => <_TappableLabel>[
1158
    for (final TimeOfDay timeOfDay in _amHours)
1159
      _buildTappableLabel(
1160
        textTheme,
1161
        color,
1162 1163 1164 1165 1166
        timeOfDay.hour,
        localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
        () {
          _selectHour(timeOfDay.hour);
        },
1167 1168
      ),
  ];
1169

1170
  List<_TappableLabel> _buildMinutes(TextTheme textTheme, Color color) {
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    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),
1184 1185
    ];

1186
    return <_TappableLabel>[
1187
      for (final TimeOfDay timeOfDay in _minuteMarkerValues)
1188 1189
        _buildTappableLabel(
          textTheme,
1190
          color,
1191 1192 1193 1194 1195 1196 1197
          timeOfDay.minute,
          localizations.formatMinute(timeOfDay),
          () {
            _selectMinute(timeOfDay.minute);
          },
        ),
    ];
1198 1199
  }

1200
  @override
1201
  Widget build(BuildContext context) {
1202
    final ThemeData theme = Theme.of(context);
1203 1204 1205
    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;
1206 1207
    final Color primaryLabelColor = MaterialStateProperty.resolveAs(pickerTheme.dialTextColor, <MaterialState>{});
    final Color secondaryLabelColor = MaterialStateProperty.resolveAs(pickerTheme.dialTextColor, <MaterialState>{MaterialState.selected});
1208 1209
    List<_TappableLabel> primaryLabels;
    List<_TappableLabel> secondaryLabels;
1210
    int selectedDialValue;
1211
    switch (widget.mode) {
1212
      case _TimePickerMode.hour:
1213
        if (widget.use24HourDials) {
1214
          selectedDialValue = widget.selectedTime.hour;
1215 1216
          primaryLabels = _build24HourRing(theme.textTheme, primaryLabelColor);
          secondaryLabels = _build24HourRing(theme.accentTextTheme, secondaryLabelColor);
1217
        } else {
1218
          selectedDialValue = widget.selectedTime.hourOfPeriod;
1219 1220
          primaryLabels = _build12HourRing(theme.textTheme, primaryLabelColor);
          secondaryLabels = _build12HourRing(theme.accentTextTheme, secondaryLabelColor);
1221
        }
1222 1223
        break;
      case _TimePickerMode.minute:
1224
        selectedDialValue = widget.selectedTime.minute;
1225 1226
        primaryLabels = _buildMinutes(theme.textTheme, primaryLabelColor);
        secondaryLabels = _buildMinutes(theme.accentTextTheme, secondaryLabelColor);
1227 1228 1229
        break;
    }

1230
    return GestureDetector(
1231
      excludeFromSemantics: true,
1232 1233 1234
      onPanStart: _handlePanStart,
      onPanUpdate: _handlePanUpdate,
      onPanEnd: _handlePanEnd,
1235
      onTapUp: _handleTapUp,
1236
      child: CustomPaint(
1237
        key: const ValueKey<String>('time-picker-dial'),
1238
        painter: _DialPainter(
1239
          selectedValue: selectedDialValue,
1240 1241
          primaryLabels: primaryLabels,
          secondaryLabels: secondaryLabels,
1242
          backgroundColor: backgroundColor,
1243 1244
          accentColor: accentColor,
          dotColor: theme.colorScheme.surface,
Yegor's avatar
Yegor committed
1245
          theta: _theta.value,
1246 1247
          textDirection: Directionality.of(context),
        ),
1248
      ),
1249 1250 1251
    );
  }
}
1252

1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
class _TimePickerInput extends StatefulWidget {
  const _TimePickerInput({
    Key key,
    @required this.initialSelectedTime,
    @required this.helpText,
    @required this.onChanged,
  }) : 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.
  final String helpText;

  final ValueChanged<TimeOfDay> onChanged;

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

class _TimePickerInputState extends State<_TimePickerInput> {
  TimeOfDay _selectedTime;
  bool hourHasError = false;
  bool minuteHasError = false;

  @override
  void initState() {
    super.initState();
    _selectedTime = widget.initialSelectedTime;
  }

  int _parseHour(String value) {
    if (value == null) {
      return null;
    }

    int newHour = int.tryParse(value);
    if (newHour == null) {
      return null;
    }

    if (MediaQuery.of(context).alwaysUse24HourFormat) {
      if (newHour >= 0 && newHour < 24) {
        return newHour;
      }
    } else {
      if (newHour > 0 && newHour < 13) {
        if ((_selectedTime.period == DayPeriod.pm && newHour != 12)
            || (_selectedTime.period == DayPeriod.am && newHour == 12)) {
          newHour = (newHour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay;
        }
        return newHour;
      }
    }
    return null;
  }

  int _parseMinute(String value) {
    if (value == null) {
      return null;
    }

    final int newMinute = int.tryParse(value);
    if (newMinute == null) {
      return null;
    }

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

  void _handleHourSavedSubmitted(String value) {
    final int newHour = _parseHour(value);
    if (newHour != null) {
      _selectedTime = TimeOfDay(hour: newHour, minute: _selectedTime.minute);
      widget.onChanged(_selectedTime);
    }
  }

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

  void _handleMinuteSavedSubmitted(String value) {
    final int newMinute = _parseMinute(value);
    if (newMinute != null) {
      _selectedTime = TimeOfDay(hour: _selectedTime.hour, minute: int.parse(value));
      widget.onChanged(_selectedTime);
    }
  }

  void _handleDayPeriodChanged(TimeOfDay value) {
    _selectedTime = value;
    widget.onChanged(_selectedTime);
  }

  String _validateHour(String value) {
    final int newHour = _parseHour(value);
    setState(() {
      hourHasError = newHour == null;
    });
    // 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;
  }

  String _validateMinute(String value) {
    final int newMinute = _parseMinute(value);
    setState(() {
      minuteHasError = newMinute == null;
    });
    // 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));
    final MediaQueryData media = MediaQuery.of(context);
    final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
    final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
    final ThemeData theme = Theme.of(context);
    final TextStyle hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? theme.textTheme.headline2;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
1394
            widget.helpText ?? MaterialLocalizations.of(context).timePickerInputHelpText,
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            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(
                  selectedTime: _selectedTime,
                  orientation: Orientation.portrait,
                  onChanged: _handleDayPeriodChanged,
                ),
                const SizedBox(width: 12.0),
              ],
              Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  const SizedBox(height: 8.0),
                  _HourMinuteTextField(
                    selectedTime: _selectedTime,
                    isHour: true,
                    style: hourMinuteStyle,
                    validator: _validateHour,
                    onSavedSubmitted: _handleHourSavedSubmitted,
                    onChanged: _handleHourChanged,
                  ),
                  const SizedBox(height: 8.0),
                  if (!hourHasError && !minuteHasError)
                    ExcludeSemantics(
1424 1425 1426 1427 1428 1429
                      child: Text(
                        MaterialLocalizations.of(context).timePickerHourLabel,
                        style: theme.textTheme.caption,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
1430 1431 1432
                    ),
                ],
              )),
1433 1434 1435
              Container(
                margin: const EdgeInsets.only(top: 8.0),
                height: _kTimePickerHeaderControlHeight,
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
                child: _StringFragment(timeOfDayFormat: timeOfDayFormat),
              ),
              Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  const SizedBox(height: 8.0),
                  _HourMinuteTextField(
                    selectedTime: _selectedTime,
                    isHour: false,
                    style: hourMinuteStyle,
                    validator: _validateMinute,
                    onSavedSubmitted: _handleMinuteSavedSubmitted,
                  ),
                  const SizedBox(height: 8.0),
                  if (!hourHasError && !minuteHasError)
                    ExcludeSemantics(
1452 1453 1454 1455 1456 1457
                      child: Text(
                        MaterialLocalizations.of(context).timePickerMinuteLabel,
                        style: theme.textTheme.caption,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
                    ),
                ],
              )),
              if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[
                const SizedBox(width: 12.0),
                _DayPeriodControl(
                  selectedTime: _selectedTime,
                  orientation: Orientation.portrait,
                  onChanged: _handleDayPeriodChanged,
                ),
              ],
            ],
          ),
          if (hourHasError || minuteHasError)
            Text(
1473
              MaterialLocalizations.of(context).invalidTimeLabel,
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
              style: theme.textTheme.bodyText2.copyWith(color: theme.colorScheme.error),
            )
          else
            const SizedBox(height: 2.0),
        ],
      ),
    );
  }
}

class _HourMinuteTextField extends StatefulWidget {
  const _HourMinuteTextField({
    Key key,
    @required this.selectedTime,
    @required this.isHour,
    @required this.style,
    @required this.validator,
    @required this.onSavedSubmitted,
    this.onChanged,
  }) : super(key: key);

  final TimeOfDay selectedTime;
  final bool isHour;
  final TextStyle style;
  final FormFieldValidator<String> validator;
  final ValueChanged<String> onSavedSubmitted;
  final ValueChanged<String> onChanged;

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

class _HourMinuteTextFieldState extends State<_HourMinuteTextField> {
  TextEditingController controller;
  FocusNode focusNode;

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

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    controller ??= TextEditingController(text: _formattedValue);
  }

  String get _formattedValue {
    final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat;
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour(
      widget.selectedTime,
      alwaysUse24HourFormat: alwaysUse24HourFormat,
    );
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
1536
    final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context);
1537 1538
    final ColorScheme colorScheme = theme.colorScheme;

1539
    final InputDecorationTheme inputDecorationTheme = timePickerTheme.inputDecorationTheme;
1540 1541 1542 1543
    InputDecoration inputDecoration;
    if (inputDecorationTheme != null) {
      inputDecoration = const InputDecoration().applyDefaults(inputDecorationTheme);
    } else {
1544
      final Color unfocusedFillColor = timePickerTheme.hourMinuteColor ?? colorScheme.onSurface.withOpacity(0.12);
1545
      inputDecoration = InputDecoration(
1546
        contentPadding: EdgeInsets.zero,
1547
        filled: true,
1548
        fillColor: focusNode.hasFocus ? Colors.transparent : unfocusedFillColor,
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
        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.
      );
    }
    inputDecoration = inputDecoration.copyWith(
      // Remove the hint text when focused because the centered cursor appears
      // odd above the hint text.
      hintText: focusNode.hasFocus ? null : _formattedValue,
    );

1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    return SizedBox(
      height: _kTimePickerHeaderControlHeight,
      child: MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
        child: TextFormField(
          expands: true,
          maxLines: null,
          focusNode: focusNode,
          textAlign: TextAlign.center,
          keyboardType: TextInputType.number,
          style: widget.style.copyWith(color: colorScheme.onSurface),
          controller: controller,
          decoration: inputDecoration,
          validator: widget.validator,
          onEditingComplete: () => widget.onSavedSubmitted(controller.text),
          onSaved: widget.onSavedSubmitted,
          onFieldSubmitted: widget.onSavedSubmitted,
          onChanged: widget.onChanged,
1590
        ),
1591
      ),
1592 1593 1594 1595
    );
  }
}

1596 1597 1598 1599 1600 1601
/// 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].
1602
class _TimePickerDialog extends StatefulWidget {
1603 1604 1605
  /// Creates a material time picker.
  ///
  /// [initialTime] must not be null.
1606
  const _TimePickerDialog({
1607
    Key key,
1608
    @required this.initialTime,
1609 1610 1611 1612
    @required this.cancelText,
    @required this.confirmText,
    @required this.helpText,
    this.initialEntryMode = TimePickerEntryMode.dial,
1613 1614
  }) : assert(initialTime != null),
       super(key: key);
1615

1616
  /// The time initially selected when the dialog is shown.
1617 1618
  final TimeOfDay initialTime;

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
  /// 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].
  final String cancelText;

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

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

1635
  @override
1636
  _TimePickerDialogState createState() => _TimePickerDialogState();
1637 1638 1639
}

class _TimePickerDialogState extends State<_TimePickerDialog> {
1640 1641
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

1642 1643 1644
  @override
  void initState() {
    super.initState();
1645
    _selectedTime = widget.initialTime;
1646 1647
    _entryMode = widget.initialEntryMode;
    _autoValidate = false;
1648 1649
  }

1650 1651 1652 1653 1654 1655 1656 1657
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    localizations = MaterialLocalizations.of(context);
    _announceInitialTimeOnce();
    _announceModeOnce();
  }

1658
  TimePickerEntryMode _entryMode;
1659
  _TimePickerMode _mode = _TimePickerMode.hour;
1660
  _TimePickerMode _lastModeAnnounced;
1661
  bool _autoValidate;
1662 1663

  TimeOfDay get selectedTime => _selectedTime;
1664
  TimeOfDay _selectedTime;
1665

1666
  Timer _vibrateTimer;
1667
  MaterialLocalizations localizations;
1668

1669 1670 1671 1672
  void _vibrate() {
    switch (Theme.of(context).platform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1673 1674
      case TargetPlatform.linux:
      case TargetPlatform.windows:
1675
        _vibrateTimer?.cancel();
1676
        _vibrateTimer = Timer(_kVibrateCommitDelay, () {
1677 1678 1679
          HapticFeedback.vibrate();
          _vibrateTimer = null;
        });
1680 1681
        break;
      case TargetPlatform.iOS:
1682
      case TargetPlatform.macOS:
1683 1684 1685 1686
        break;
    }
  }

1687
  void _handleModeChanged(_TimePickerMode mode) {
1688
    _vibrate();
1689 1690
    setState(() {
      _mode = mode;
1691
      _announceModeOnce();
1692 1693 1694
    });
  }

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  void _handleEntryModeToggle() {
    setState(() {
      switch (_entryMode) {
        case TimePickerEntryMode.dial:
          _autoValidate = false;
          _entryMode = TimePickerEntryMode.input;
          break;
        case TimePickerEntryMode.input:
          _formKey.currentState.save();
          _entryMode = TimePickerEntryMode.dial;
          break;
      }
    });
  }

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
  void _announceModeOnce() {
    if (_lastModeAnnounced == _mode) {
      // Already announced it.
      return;
    }

    switch (_mode) {
      case _TimePickerMode.hour:
        _announceToAccessibility(context, localizations.timePickerHourModeAnnouncement);
        break;
      case _TimePickerMode.minute:
        _announceToAccessibility(context, localizations.timePickerMinuteModeAnnouncement);
        break;
    }
    _lastModeAnnounced = _mode;
  }

  bool _announcedInitialTime = false;

  void _announceInitialTimeOnce() {
    if (_announcedInitialTime)
      return;

    final MediaQueryData media = MediaQuery.of(context);
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    _announceToAccessibility(
      context,
      localizations.formatTimeOfDay(widget.initialTime, alwaysUse24HourFormat: media.alwaysUse24HourFormat),
    );
    _announcedInitialTime = true;
  }

1742
  void _handleTimeChanged(TimeOfDay value) {
1743
    _vibrate();
1744 1745 1746 1747 1748
    setState(() {
      _selectedTime = value;
    });
  }

1749 1750 1751 1752 1753 1754
  void _handleHourSelected() {
    setState(() {
      _mode = _TimePickerMode.minute;
    });
  }

1755 1756 1757 1758 1759
  void _handleCancel() {
    Navigator.pop(context);
  }

  void _handleOk() {
1760 1761 1762 1763 1764 1765 1766 1767
    if (_entryMode == TimePickerEntryMode.input) {
      final FormState form = _formKey.currentState;
      if (!form.validate()) {
        setState(() { _autoValidate = true; });
        return;
      }
      form.save();
    }
1768 1769 1770
    Navigator.pop(context, _selectedTime);
  }

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
  Size _dialogSize(BuildContext context) {
    final Orientation orientation = MediaQuery.of(context).orientation;
    final ThemeData theme = Theme.of(context);
    // 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.
    final double textScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 1.1);

    double timePickerWidth;
    double timePickerHeight;
    switch (_entryMode) {
      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);
  }

1806 1807
  @override
  Widget build(BuildContext context) {
1808 1809 1810
    assert(debugCheckHasMediaQuery(context));
    final MediaQueryData media = MediaQuery.of(context);
    final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
1811
    final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
1812
    final ThemeData theme = Theme.of(context);
1813 1814
    final ShapeBorder shape = TimePickerTheme.of(context).shape ?? _kDefaultShape;
    final Orientation orientation = media.orientation;
Yegor's avatar
Yegor committed
1815

1816
    final Widget actions = Row(
1817
      children: <Widget>[
1818 1819 1820 1821 1822 1823 1824 1825
        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,
          icon: Icon(_entryMode == TimePickerEntryMode.dial ? Icons.keyboard : Icons.access_time),
          tooltip: _entryMode == TimePickerEntryMode.dial
1826 1827
              ? MaterialLocalizations.of(context).inputTimeModeButtonLabel
              : MaterialLocalizations.of(context).dialModeButtonLabel,
1828
        ),
1829 1830 1831 1832 1833
        Expanded(
          // TODO(rami-a): Move away from ButtonBar to avoid https://github.com/flutter/flutter/issues/53378.
          child: ButtonBar(
            layoutBehavior: ButtonBarLayoutBehavior.constrained,
            children: <Widget>[
1834
              TextButton(
1835 1836 1837
                onPressed: _handleCancel,
                child: Text(widget.cancelText ?? localizations.cancelButtonLabel),
              ),
1838
              TextButton(
1839 1840 1841 1842 1843
                onPressed: _handleOk,
                child: Text(widget.confirmText ?? localizations.okButtonLabel),
              ),
            ],
          ),
1844 1845
        ),
      ],
1846 1847
    );

1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
    Widget picker;
    switch (_entryMode) {
      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(
                mode: _mode,
                use24HourDials: use24HourDials,
                selectedTime: _selectedTime,
                onChanged: _handleTimeChanged,
                onHourSelected: _handleHourSelected,
              ),
            ),
          ),
        );

        final Widget header = _TimePickerHeader(
          selectedTime: _selectedTime,
          mode: _mode,
          orientation: orientation,
          onModeChanged: _handleModeChanged,
          onChanged: _handleTimeChanged,
          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,
          autovalidate: _autoValidate,
          child: SingleChildScrollView(
1919
            child: Column(
1920 1921
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
1922 1923 1924 1925 1926
                _TimePickerInput(
                  initialSelectedTime: _selectedTime,
                  helpText: widget.helpText,
                  onChanged: _handleTimeChanged,
                ),
1927 1928 1929
                actions,
              ],
            ),
1930 1931 1932 1933
          ),
        );
        break;
    }
1934

1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    final Size dialogSize = _dialogSize(context);
    return Dialog(
      shape: shape,
      backgroundColor: TimePickerTheme.of(context).backgroundColor ?? theme.colorScheme.surface,
      insetPadding: EdgeInsets.symmetric(
        horizontal: 16.0,
        vertical: _entryMode == TimePickerEntryMode.input ? 0.0 : 24.0,
      ),
      child: AnimatedContainer(
        width: dialogSize.width,
        height: dialogSize.height,
        duration: _kDialogSizeAnimationDuration,
        curve: Curves.easeIn,
        child: picker,
1949 1950
      ),
    );
1951
  }
1952 1953 1954 1955 1956 1957 1958

  @override
  void dispose() {
    _vibrateTimer?.cancel();
    _vibrateTimer = null;
    super.dispose();
  }
1959 1960 1961 1962 1963
}

/// Shows a dialog containing a material design time picker.
///
/// The returned Future resolves to the time selected by the user when the user
1964
/// closes the dialog. If the user cancels the dialog, null is returned.
1965
///
1966
/// {@tool snippet}
1967
/// Show a dialog with [initialTime] equal to the current time.
Ian Hickson's avatar
Ian Hickson committed
1968
///
1969
/// ```dart
1970
/// Future<TimeOfDay> selectedTime = showTimePicker(
1971
///   initialTime: TimeOfDay.now(),
Ian Hickson's avatar
Ian Hickson committed
1972
///   context: context,
1973 1974
/// );
/// ```
1975
/// {@end-tool}
1976
///
1977 1978
/// 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
1979
///
1980 1981 1982 1983
/// The [builder] parameter can be used to wrap the dialog widget
/// to add inherited widgets like [Localizations.override],
/// [Directionality], or [MediaQuery].
///
1984 1985 1986 1987 1988 1989 1990
/// The [entryMode] parameter can be used to
/// determine the initial time entry selection of the picker (either a clock
/// dial or text input).
///
/// Optional strings for the [helpText], [cancelText], and [confirmText] can be
/// provided to override the default values.
///
1991
/// {@tool snippet}
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
/// Show a dialog with the text direction overridden to be [TextDirection.rtl].
///
/// ```dart
/// Future<TimeOfDay> selectedTimeRTL = showTimePicker(
///   context: context,
///   initialTime: TimeOfDay.now(),
///   builder: (BuildContext context, Widget child) {
///     return Directionality(
///       textDirection: TextDirection.rtl,
///       child: child,
///     );
///   },
/// );
/// ```
/// {@end-tool}
///
2008
/// {@tool snippet}
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
/// Show a dialog with time unconditionally displayed in 24 hour format.
///
/// ```dart
/// Future<TimeOfDay> selectedTime24Hour = showTimePicker(
///   context: context,
///   initialTime: TimeOfDay(hour: 10, minute: 47),
///   builder: (BuildContext context, Widget child) {
///     return MediaQuery(
///       data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
///       child: child,
///     );
///   },
/// );
/// ```
/// {@end-tool}
///
2025 2026
/// See also:
///
2027 2028
///  * [showDatePicker], which shows a dialog that contains a material design
///    date picker.
2029
Future<TimeOfDay> showTimePicker({
2030
  @required BuildContext context,
2031 2032
  @required TimeOfDay initialTime,
  TransitionBuilder builder,
2033
  bool useRootNavigator = true,
2034 2035 2036 2037
  TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial,
  String cancelText,
  String confirmText,
  String helpText,
2038
  RouteSettings routeSettings,
2039
}) async {
2040
  assert(context != null);
2041
  assert(initialTime != null);
2042
  assert(useRootNavigator != null);
2043
  assert(initialEntryMode != null);
2044
  assert(debugCheckHasMaterialLocalizations(context));
2045

2046 2047 2048 2049 2050 2051 2052
  final Widget dialog = _TimePickerDialog(
    initialTime: initialTime,
    initialEntryMode: initialEntryMode,
    cancelText: cancelText,
    confirmText: confirmText,
    helpText: helpText,
  );
2053
  return await showDialog<TimeOfDay>(
2054
    context: context,
2055
    useRootNavigator: useRootNavigator,
2056 2057 2058
    builder: (BuildContext context) {
      return builder == null ? dialog : builder(context, dialog);
    },
2059
    routeSettings: routeSettings,
2060
  );
2061
}
2062 2063 2064 2065

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