date_picker.dart 78.6 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
import 'dart:math' as math;

7
import 'package:flutter/scheduler.dart';
8 9 10 11 12
import 'package:flutter/widgets.dart';

import 'colors.dart';
import 'localizations.dart';
import 'picker.dart';
13
import 'theme.dart';
14

15 16
// Values derived from https://developer.apple.com/design/resources/ and on iOS
// simulators with "Debug View Hierarchy".
17
const double _kItemExtent = 32.0;
18 19 20
// From the picker's intrinsic content size constraint.
const double _kPickerWidth = 320.0;
const double _kPickerHeight = 216.0;
21
const bool _kUseMagnifier = true;
22
const double _kMagnification = 2.35/2.1;
23
const double _kDatePickerPadSize = 12.0;
24 25 26
// The density of a date picker is different from a generic picker.
// Eyeballed from iOS.
const double _kSqueeze = 1.25;
27

28 29 30 31
const TextStyle _kDefaultPickerTextStyle = TextStyle(
  letterSpacing: -0.83,
);

32 33 34 35 36 37 38 39 40 41 42 43
// The item height is 32 and the magnifier height is 34, from
// iOS simulators with "Debug View Hierarchy".
// And the magnified fontSize by [_kTimerPickerMagnification] conforms to the
// iOS 14 native style by eyeball test.
const double _kTimerPickerMagnification = 34 / 32;
// Minimum horizontal padding between [CupertinoTimerPicker]
//
// It shouldn't actually be hard-coded for direct use, and the perfect solution
// should be to calculate the values that match the magnified values by
// offAxisFraction and _kSqueeze.
// Such calculations are complex, so we'll hard-code them for now.
const double _kTimerPickerMinHorizontalPadding = 30;
44
// Half of the horizontal padding value between the timer picker's columns.
45
const double _kTimerPickerHalfColumnPadding = 4;
46 47
// The horizontal padding between the timer picker's number label and its
// corresponding unit label.
48
const double _kTimerPickerLabelPadSize = 6;
49 50
const double _kTimerPickerLabelFontSize = 17.0;

51
// The width of each column of the countdown time picker.
52 53
const double _kTimerPickerColumnIntrinsicWidth = 106;

54 55 56
TextStyle _themeTextStyle(BuildContext context, { bool isValid = true }) {
  final TextStyle style = CupertinoTheme.of(context).textTheme.dateTimePickerTextStyle;
  return isValid ? style : style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context));
57 58
}

59 60 61 62 63 64 65 66
void _animateColumnControllerToItem(FixedExtentScrollController controller, int targetItem) {
  controller.animateToItem(
    targetItem,
    curve: Curves.easeInOut,
    duration: const Duration(milliseconds: 200),
  );
}

67
const Widget _leftSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capRightEdge: false);
68
const Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capLeftEdge: false, capRightEdge: false);
69 70
const Widget _rightSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capLeftEdge: false);

71 72 73 74 75 76 77 78 79
// Lays out the date picker based on how much space each single column needs.
//
// Each column is a child of this delegate, indexed from 0 to number of columns - 1.
// Each column will be padded horizontally by 12.0 both left and right.
//
// The picker will be placed in the center, and the leftmost and rightmost
// column will be extended equally to the remaining width.
class _DatePickerLayoutDelegate extends MultiChildLayoutDelegate {
  _DatePickerLayoutDelegate({
80 81
    required this.columnWidths,
    required this.textDirectionFactor,
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }) : assert(columnWidths != null),
       assert(textDirectionFactor != null);

  // The list containing widths of all columns.
  final List<double> columnWidths;

  // textDirectionFactor is 1 if text is written left to right, and -1 if right to left.
  final int textDirectionFactor;

  @override
  void performLayout(Size size) {
    double remainingWidth = size.width;

    for (int i = 0; i < columnWidths.length; i++)
      remainingWidth -= columnWidths[i] + _kDatePickerPadSize * 2;

    double currentHorizontalOffset = 0.0;

    for (int i = 0; i < columnWidths.length; i++) {
      final int index = textDirectionFactor == 1 ? i : columnWidths.length - i - 1;

      double childWidth = columnWidths[index] + _kDatePickerPadSize * 2;
      if (index == 0 || index == columnWidths.length - 1)
        childWidth += remainingWidth / 2;

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
      // We can't actually assert here because it would break things badly for
      // semantics, which will expect that we laid things out here.
      assert(() {
        if (childWidth < 0) {
          FlutterError.reportError(
            FlutterErrorDetails(
              exception: FlutterError(
                'Insufficient horizontal space to render the '
                'CupertinoDatePicker because the parent is too narrow at '
                '${size.width}px.\n'
                'An additional ${-remainingWidth}px is needed to avoid '
                'overlapping columns.',
              ),
            ),
          );
        }
        return true;
      }());
      layoutChild(index, BoxConstraints.tight(Size(math.max(0.0, childWidth), size.height)));
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
      positionChild(index, Offset(currentHorizontalOffset, 0.0));

      currentHorizontalOffset += childWidth;
    }
  }

  @override
  bool shouldRelayout(_DatePickerLayoutDelegate oldDelegate) {
    return columnWidths != oldDelegate.columnWidths
      || textDirectionFactor != oldDelegate.textDirectionFactor;
  }
}

/// Different display modes of [CupertinoDatePicker].
///
/// See also:
///
///  * [CupertinoDatePicker], the class that implements different display modes
144
///    of the iOS-style date picker.
145 146 147 148 149 150
///  * [CupertinoPicker], the class that implements a content agnostic spinner UI.
enum CupertinoDatePickerMode {
  /// Mode that shows the date in hour, minute, and (optional) an AM/PM designation.
  /// The AM/PM designation is shown only if [CupertinoDatePicker] does not use 24h format.
  /// Column order is subject to internationalization.
  ///
151
  /// Example: ` 4 | 14 | PM `.
152 153 154 155 156
  time,
  /// Mode that shows the date in month, day of month, and year.
  /// Name of month is spelled in full.
  /// Column order is subject to internationalization.
  ///
157
  /// Example: ` July | 13 | 2012 `.
158 159 160 161 162 163
  date,
  /// Mode that shows the date as day of the week, month, day of month and
  /// the time in hour, minute, and (optional) an AM/PM designation.
  /// The AM/PM designation is shown only if [CupertinoDatePicker] does not use 24h format.
  /// Column order is subject to internationalization.
  ///
164
  /// Example: ` Fri Jul 13 | 4 | 14 | PM `
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  dateAndTime,
}

// Different types of column in CupertinoDatePicker.
enum _PickerColumnType {
  // Day of month column in date mode.
  dayOfMonth,
  // Month column in date mode.
  month,
  // Year column in date mode.
  year,
  // Medium date column in dateAndTime mode.
  date,
  // Hour column in time and dateAndTime mode.
  hour,
  // minute column in time and dateAndTime mode.
  minute,
  // AM/PM column in time and dateAndTime mode.
  dayPeriod,
}

/// A date picker widget in iOS style.
///
/// There are several modes of the date picker listed in [CupertinoDatePickerMode].
///
/// The class will display its children as consecutive columns. Its children
/// order is based on internationalization.
///
/// Example of the picker in date mode:
///
195 196
///  * US-English: `| July | 13 | 2012 |`
///  * Vietnamese: `| 13 | Tháng 7 | 2012 |`
197
///
198 199 200 201 202 203 204
/// Can be used with [showCupertinoModalPopup] to display the picker modally at
/// the bottom of the screen.
///
/// Sizes itself to its parent and may not render correctly if not given the
/// full screen width. Content texts are shown with
/// [CupertinoTextThemeData.dateTimePickerTextStyle].
///
205 206 207 208 209 210 211 212 213 214 215
/// See also:
///
///  * [CupertinoTimerPicker], the class that implements the iOS-style timer picker.
///  * [CupertinoPicker], the class that implements a content agnostic spinner UI.
class CupertinoDatePicker extends StatefulWidget {
  /// Constructs an iOS style date picker.
  ///
  /// [mode] is one of the mode listed in [CupertinoDatePickerMode] and defaults
  /// to [CupertinoDatePickerMode.dateAndTime].
  ///
  /// [onDateTimeChanged] is the callback called when the selected date or time
216
  /// changes and must not be null. When in [CupertinoDatePickerMode.time] mode,
217 218 219
  /// the year, month and day will be the same as [initialDateTime]. When in
  /// [CupertinoDatePickerMode.date] mode, this callback will always report the
  /// start time of the currently selected day.
220 221 222 223 224 225
  ///
  /// [initialDateTime] is the initial date time of the picker. Defaults to the
  /// present date and time and must not be null. The present must conform to
  /// the intervals set in [minimumDate], [maximumDate], [minimumYear], and
  /// [maximumYear].
  ///
226 227 228 229 230
  /// [minimumDate] is the minimum selectable [DateTime] of the picker. When set
  /// to null, the picker does not limit the minimum [DateTime] the user can pick.
  /// In [CupertinoDatePickerMode.time] mode, [minimumDate] should typically be
  /// on the same date as [initialDateTime], as the picker will not limit the
  /// minimum time the user can pick if it's set to a date earlier than that.
231
  ///
232 233 234 235 236
  /// [maximumDate] is the maximum selectable [DateTime] of the picker. When set
  /// to null, the picker does not limit the maximum [DateTime] the user can pick.
  /// In [CupertinoDatePickerMode.time] mode, [maximumDate] should typically be
  /// on the same date as [initialDateTime], as the picker will not limit the
  /// maximum time the user can pick if it's set to a date later than that.
237 238 239 240 241 242 243 244 245 246 247 248
  ///
  /// [minimumYear] is the minimum year that the picker can be scrolled to in
  /// [CupertinoDatePickerMode.date] mode. Defaults to 1 and must not be null.
  ///
  /// [maximumYear] is the maximum year that the picker can be scrolled to in
  /// [CupertinoDatePickerMode.date] mode. Null if there's no limit.
  ///
  /// [minuteInterval] is the granularity of the minute spinner. Must be a
  /// positive integer factor of 60.
  ///
  /// [use24hFormat] decides whether 24 hour format is used. Defaults to false.
  CupertinoDatePicker({
249
    Key? key,
250
    this.mode = CupertinoDatePickerMode.dateAndTime,
251 252
    required this.onDateTimeChanged,
    DateTime? initialDateTime,
253 254 255 256 257 258
    this.minimumDate,
    this.maximumDate,
    this.minimumYear = 1,
    this.maximumYear,
    this.minuteInterval = 1,
    this.use24hFormat = false,
259
    this.backgroundColor,
260
  }) : initialDateTime = initialDateTime ?? DateTime.now(),
261 262 263 264 265 266
       assert(mode != null),
       assert(onDateTimeChanged != null),
       assert(minimumYear != null),
       assert(
         minuteInterval > 0 && 60 % minuteInterval == 0,
         'minute interval is not a positive integer factor of 60',
267 268
       ),
       super(key: key) {
269 270
    assert(this.initialDateTime != null);
    assert(
271
      mode != CupertinoDatePickerMode.dateAndTime || minimumDate == null || !this.initialDateTime.isBefore(minimumDate!),
272 273 274
      'initial date is before minimum date',
    );
    assert(
275
      mode != CupertinoDatePickerMode.dateAndTime || maximumDate == null || !this.initialDateTime.isAfter(maximumDate!),
276 277 278 279
      'initial date is after maximum date',
    );
    assert(
      mode != CupertinoDatePickerMode.date || (minimumYear >= 1 && this.initialDateTime.year >= minimumYear),
280
      'initial year is not greater than minimum year, or minimum year is not positive',
281 282
    );
    assert(
283
      mode != CupertinoDatePickerMode.date || maximumYear == null || this.initialDateTime.year <= maximumYear!,
284 285
      'initial year is not smaller than maximum year',
    );
286
    assert(
287
      mode != CupertinoDatePickerMode.date || minimumDate == null || !minimumDate!.isAfter(this.initialDateTime),
Tomohiro Hattori's avatar
Tomohiro Hattori committed
288
      'initial date ${this.initialDateTime} is not greater than or equal to minimumDate $minimumDate',
289 290
    );
    assert(
291
      mode != CupertinoDatePickerMode.date || maximumDate == null || !maximumDate!.isBefore(this.initialDateTime),
Tomohiro Hattori's avatar
Tomohiro Hattori committed
292
      'initial date ${this.initialDateTime} is not less than or equal to maximumDate $maximumDate',
293
    );
294 295 296 297 298
    assert(
      this.initialDateTime.minute % minuteInterval == 0,
      'initial minute is not divisible by minute interval',
    );
  }
299 300 301 302 303 304 305 306 307 308 309 310 311 312

  /// The mode of the date picker as one of [CupertinoDatePickerMode].
  /// Defaults to [CupertinoDatePickerMode.dateAndTime]. Cannot be null and
  /// value cannot change after initial build.
  final CupertinoDatePickerMode mode;

  /// The initial date and/or time of the picker. Defaults to the present date
  /// and time and must not be null. The present must conform to the intervals
  /// set in [minimumDate], [maximumDate], [minimumYear], and [maximumYear].
  ///
  /// Changing this value after the initial build will not affect the currently
  /// selected date time.
  final DateTime initialDateTime;

313 314 315
  /// The minimum selectable date that the picker can settle on.
  ///
  /// When non-null, the user can still scroll the picker to [DateTime]s earlier
316
  /// than [minimumDate], but the [onDateTimeChanged] will not be called on
317 318 319 320 321 322 323 324 325
  /// these [DateTime]s. Once let go, the picker will scroll back to [minimumDate].
  ///
  /// In [CupertinoDatePickerMode.time] mode, a time becomes unselectable if the
  /// [DateTime] produced by combining that particular time and the date part of
  /// [initialDateTime] is earlier than [minimumDate]. So typically [minimumDate]
  /// needs to be set to a [DateTime] that is on the same date as [initialDateTime].
  ///
  /// Defaults to null. When set to null, the picker does not impose a limit on
  /// the earliest [DateTime] the user can select.
326
  final DateTime? minimumDate;
327

328 329 330
  /// The maximum selectable date that the picker can settle on.
  ///
  /// When non-null, the user can still scroll the picker to [DateTime]s later
331
  /// than [maximumDate], but the [onDateTimeChanged] will not be called on
332 333 334 335 336 337 338 339 340
  /// these [DateTime]s. Once let go, the picker will scroll back to [maximumDate].
  ///
  /// In [CupertinoDatePickerMode.time] mode, a time becomes unselectable if the
  /// [DateTime] produced by combining that particular time and the date part of
  /// [initialDateTime] is later than [maximumDate]. So typically [maximumDate]
  /// needs to be set to a [DateTime] that is on the same date as [initialDateTime].
  ///
  /// Defaults to null. When set to null, the picker does not impose a limit on
  /// the latest [DateTime] the user can select.
341
  final DateTime? maximumDate;
342 343 344 345 346 347 348

  /// Minimum year that the picker can be scrolled to in
  /// [CupertinoDatePickerMode.date] mode. Defaults to 1 and must not be null.
  final int minimumYear;

  /// Maximum year that the picker can be scrolled to in
  /// [CupertinoDatePickerMode.date] mode. Null if there's no limit.
349
  final int? maximumYear;
350 351 352 353 354 355 356 357

  /// The granularity of the minutes spinner, if it is shown in the current mode.
  /// Must be an integer factor of 60.
  final int minuteInterval;

  /// Whether to use 24 hour format. Defaults to false.
  final bool use24hFormat;

358 359 360
  /// Callback called when the selected date and/or time changes. If the new
  /// selected [DateTime] is not valid, or is not in the [minimumDate] through
  /// [maximumDate] range, this callback will not be called.
361 362
  ///
  /// Must not be null.
363 364
  final ValueChanged<DateTime> onDateTimeChanged;

365 366
  /// Background color of date picker.
  ///
367
  /// Defaults to null, which disables background painting entirely.
368
  final Color? backgroundColor;
369

370
  @override
Ian Hickson's avatar
Ian Hickson committed
371
  State<StatefulWidget> createState() { // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499
372 373 374 375
    // The `time` mode and `dateAndTime` mode of the picker share the time
    // columns, so they are placed together to one state.
    // The `date` mode has different children and is implemented in a different
    // state.
376 377 378 379 380 381 382
    switch (mode) {
      case CupertinoDatePickerMode.time:
      case CupertinoDatePickerMode.dateAndTime:
        return _CupertinoDatePickerDateTimeState();
      case CupertinoDatePickerMode.date:
        return _CupertinoDatePickerDateState();
    }
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  }

  // Estimate the minimum width that each column needs to layout its content.
  static double _getColumnWidth(
    _PickerColumnType columnType,
    CupertinoLocalizations localizations,
    BuildContext context,
  ) {
    String longestText = '';

    switch (columnType) {
      case _PickerColumnType.date:
        // Measuring the length of all possible date is impossible, so here
        // just some dates are measured.
        for (int i = 1; i <= 12; i++) {
          // An arbitrary date.
          final String date =
              localizations.datePickerMediumDate(DateTime(2018, i, 25));
          if (longestText.length < date.length)
            longestText = date;
        }
        break;
      case _PickerColumnType.hour:
406
        for (int i = 0; i < 24; i++) {
407 408 409 410 411 412
          final String hour = localizations.datePickerHour(i);
          if (longestText.length < hour.length)
            longestText = hour;
        }
        break;
      case _PickerColumnType.minute:
413
        for (int i = 0; i < 60; i++) {
414 415 416 417 418 419 420 421 422 423 424 425
          final String minute = localizations.datePickerMinute(i);
          if (longestText.length < minute.length)
            longestText = minute;
        }
        break;
      case _PickerColumnType.dayPeriod:
        longestText =
          localizations.anteMeridiemAbbreviation.length > localizations.postMeridiemAbbreviation.length
            ? localizations.anteMeridiemAbbreviation
            : localizations.postMeridiemAbbreviation;
        break;
      case _PickerColumnType.dayOfMonth:
426
        for (int i = 1; i <=31; i++) {
427 428 429 430 431 432
          final String dayOfMonth = localizations.datePickerDayOfMonth(i);
          if (longestText.length < dayOfMonth.length)
            longestText = dayOfMonth;
        }
        break;
      case _PickerColumnType.month:
433
        for (int i = 1; i <=12; i++) {
434 435 436 437 438 439 440 441 442 443 444 445 446 447
          final String month = localizations.datePickerMonth(i);
          if (longestText.length < month.length)
            longestText = month;
        }
        break;
      case _PickerColumnType.year:
        longestText = localizations.datePickerYear(2018);
        break;
    }

    assert(longestText != '', 'column type is not appropriate');

    final TextPainter painter = TextPainter(
      text: TextSpan(
448
        style: _themeTextStyle(context),
449 450 451 452 453 454 455 456 457 458 459 460 461 462
        text: longestText,
      ),
      textDirection: Directionality.of(context),
    );

    // This operation is expensive and should be avoided. It is called here only
    // because there's no other way to get the information we want without
    // laying out the text.
    painter.layout();

    return painter.maxIntrinsicWidth;
  }
}

463
typedef _ColumnBuilder = Widget Function(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay);
464 465

class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {
466 467 468 469
  // Fraction of the farthest column's vanishing point vs its width. Eyeballed
  // vs iOS.
  static const double _kMaximumOffAxisFraction = 0.45;

470 471
  late int textDirectionFactor;
  late CupertinoLocalizations localizations;
472 473 474

  // Alignment based on text direction. The variable name is self descriptive,
  // however, when text direction is rtl, alignment is reversed.
475 476
  late Alignment alignCenterLeft;
  late Alignment alignCenterRight;
477 478 479

  // Read this out when the state is initially created. Changes in initialDateTime
  // in the widget after first build is ignored.
480
  late DateTime initialDateTime;
481

482
  // The difference in days between the initial date and the currently selected date.
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  // 0 if the current mode does not involve a date.
  int get selectedDayFromInitial {
    switch (widget.mode) {
      case CupertinoDatePickerMode.dateAndTime:
        return dateController.hasClients ? dateController.selectedItem : 0;
      case CupertinoDatePickerMode.time:
        return 0;
      case CupertinoDatePickerMode.date:
        break;
    }
    assert(
      false,
      '$runtimeType is only meant for dateAndTime mode or time mode',
    );
    return 0;
  }
  // The controller of the date column.
500
  late FixedExtentScrollController dateController;
501 502 503 504 505 506 507 508 509 510

  // The current selection of the hour picker. Values range from 0 to 23.
  int get selectedHour => _selectedHour(selectedAmPm, _selectedHourIndex);
  int get _selectedHourIndex => hourController.hasClients ? hourController.selectedItem % 24 : initialDateTime.hour;
  // Calculates the selected hour given the selected indices of the hour picker
  // and the meridiem picker.
  int _selectedHour(int selectedAmPm, int selectedHour) {
    return _isHourRegionFlipped(selectedAmPm) ? (selectedHour + 12) % 24 : selectedHour;
  }
  // The controller of the hour column.
511
  late FixedExtentScrollController hourController;
512 513

  // The current selection of the minute picker. Values range from 0 to 59.
514 515 516 517 518 519
  int get selectedMinute {
    return minuteController.hasClients
      ? minuteController.selectedItem * widget.minuteInterval % 60
      : initialDateTime.minute;
  }
  // The controller of the minute column.
520
  late FixedExtentScrollController minuteController;
521

522 523 524 525 526 527
  // Whether the current meridiem selection is AM or PM.
  //
  // We can't use the selectedItem of meridiemController as the source of truth
  // because the meridiem picker can be scrolled **animatedly** by the hour picker
  // (e.g. if you scroll from 12 to 1 in 12h format), but the meridiem change
  // should take effect immediately, **before** the animation finishes.
528
  late int selectedAmPm;
529 530 531 532 533 534 535 536 537 538 539 540
  // Whether the physical-region-to-meridiem mapping is flipped.
  bool get isHourRegionFlipped => _isHourRegionFlipped(selectedAmPm);
  bool _isHourRegionFlipped(int selectedAmPm) => selectedAmPm != meridiemRegion;
  // The index of the 12-hour region the hour picker is currently in.
  //
  // Used to determine whether the meridiemController should start animating.
  // Valid values are 0 and 1.
  //
  // The AM/PM correspondence of the two regions flips when the meridiem picker
  // scrolls. This variable is to keep track of the selected "physical"
  // (meridiem picker invariant) region of the hour picker. The "physical" region
  // of an item of index `i` is `i ~/ 12`.
541
  late int meridiemRegion;
542 543 544 545
  // The current selection of the AM/PM picker.
  //
  // - 0 means AM
  // - 1 means PM
546
  late FixedExtentScrollController meridiemController;
547 548 549 550 551 552 553 554 555 556 557 558

  bool isDatePickerScrolling = false;
  bool isHourPickerScrolling = false;
  bool isMinutePickerScrolling = false;
  bool isMeridiemPickerScrolling = false;

  bool get isScrolling {
    return isDatePickerScrolling
        || isHourPickerScrolling
        || isMinutePickerScrolling
        || isMeridiemPickerScrolling;
  }
559

560
  // The estimated width of columns.
561 562 563 564 565 566 567
  final Map<int, double> estimatedColumnWidths = <int, double>{};

  @override
  void initState() {
    super.initState();
    initialDateTime = widget.initialDateTime;

568 569 570 571 572 573
    // Initially each of the "physical" regions is mapped to the meridiem region
    // with the same number, e.g., the first 12 items are mapped to the first 12
    // hours of a day. Such mapping is flipped when the meridiem picker is scrolled
    // by the user, the first 12 items are mapped to the last 12 hours of a day.
    selectedAmPm = initialDateTime.hour ~/ 12;
    meridiemRegion = selectedAmPm;
574

575 576 577 578
    meridiemController = FixedExtentScrollController(initialItem: selectedAmPm);
    hourController = FixedExtentScrollController(initialItem: initialDateTime.hour);
    minuteController = FixedExtentScrollController(initialItem: initialDateTime.minute ~/ widget.minuteInterval);
    dateController = FixedExtentScrollController(initialItem: 0);
579

580
    PaintingBinding.instance!.systemFonts.addListener(_handleSystemFontsChange);
581 582 583 584 585 586 587 588 589 590 591 592 593
  }

  void _handleSystemFontsChange () {
    setState(() {
      // System fonts change might cause the text layout width to change.
      // Clears cached width to ensure that they get recalculated with the
      // new system fonts.
      estimatedColumnWidths.clear();
    });
  }

  @override
  void dispose() {
594 595 596 597 598
    dateController.dispose();
    hourController.dispose();
    minuteController.dispose();
    meridiemController.dispose();

599
    PaintingBinding.instance!.systemFonts.removeListener(_handleSystemFontsChange);
600
    super.dispose();
601 602 603 604 605 606 607 608
  }

  @override
  void didUpdateWidget(CupertinoDatePicker oldWidget) {
    super.didUpdateWidget(oldWidget);

    assert(
      oldWidget.mode == widget.mode,
609
      "The $runtimeType's mode cannot change once it's built.",
610
    );
611 612 613 614 615 616 617

    if (!widget.use24hFormat && oldWidget.use24hFormat) {
      // Thanks to the physical and meridiem region mapping, the only thing we
      // need to update is the meridiem controller, if it's not previously attached.
      meridiemController.dispose();
      meridiemController = FixedExtentScrollController(initialItem: selectedAmPm);
    }
618 619 620 621 622 623 624
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    textDirectionFactor = Directionality.of(context) == TextDirection.ltr ? 1 : -1;
625
    localizations = CupertinoLocalizations.of(context);
626 627 628 629 630 631 632 633 634 635 636 637 638 639

    alignCenterLeft = textDirectionFactor == 1 ? Alignment.centerLeft : Alignment.centerRight;
    alignCenterRight = textDirectionFactor == 1 ? Alignment.centerRight : Alignment.centerLeft;

    estimatedColumnWidths.clear();
  }

  // Lazily calculate the column width of the column being displayed only.
  double _getEstimatedColumnWidth(_PickerColumnType columnType) {
    if (estimatedColumnWidths[columnType.index] == null) {
      estimatedColumnWidths[columnType.index] =
          CupertinoDatePicker._getColumnWidth(columnType, localizations, context);
    }

640
    return estimatedColumnWidths[columnType.index]!;
641 642 643
  }

  // Gets the current date time of the picker.
644 645
  DateTime get selectedDateTime {
    return DateTime(
646 647
      initialDateTime.year,
      initialDateTime.month,
648 649
      initialDateTime.day + selectedDayFromInitial,
      selectedHour,
650 651 652 653
      selectedMinute,
    );
  }

654 655 656 657 658 659 660 661 662 663 664 665 666
  // Only reports datetime change when the date time is valid.
  void _onSelectedItemChange(int index) {
    final DateTime selected = selectedDateTime;

    final bool isDateInvalid = widget.minimumDate?.isAfter(selected) == true
                            || widget.maximumDate?.isBefore(selected) == true;

    if (isDateInvalid)
      return;

    widget.onDateTimeChanged(selected);
  }

667
  // Builds the date column. The date is displayed in medium date format (e.g. Fri Aug 31).
668
  Widget _buildMediumDatePicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
669 670 671 672 673 674 675
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isDatePickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isDatePickerScrolling = false;
          _pickerDidStopScrolling();
676 677
        }

678
        return false;
679
      },
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
      child: CupertinoPicker.builder(
        scrollController: dateController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: (int index) {
          _onSelectedItemChange(index);
        },
        itemBuilder: (BuildContext context, int index) {
          final DateTime rangeStart = DateTime(
            initialDateTime.year,
            initialDateTime.month,
            initialDateTime.day + index,
          );

          // Exclusive.
          final DateTime rangeEnd = DateTime(
            initialDateTime.year,
            initialDateTime.month,
            initialDateTime.day + index + 1,
          );

          final DateTime now = DateTime.now();

707
          if (widget.minimumDate?.isBefore(rangeEnd) == false)
708 709 710 711 712 713 714 715 716 717 718 719 720
            return null;
          if (widget.maximumDate?.isAfter(rangeStart) == false)
            return null;

          final String dateText = rangeStart == DateTime(now.year, now.month, now.day)
            ? localizations.todayLabel
            : localizations.datePickerMediumDate(rangeStart);

          return itemPositioningBuilder(
            context,
            Text(dateText, style: _themeTextStyle(context)),
          );
        },
721
        selectionOverlay: selectionOverlay,
722
      ),
723 724 725
    );
  }

726
  // With the meridiem picker set to `meridiemIndex`, and the hour picker set to
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  // `hourIndex`, is it possible to change the value of the minute picker, so
  // that the resulting date stays in the valid range.
  bool _isValidHour(int meridiemIndex, int hourIndex) {
    final DateTime rangeStart = DateTime(
      initialDateTime.year,
      initialDateTime.month,
      initialDateTime.day + selectedDayFromInitial,
      _selectedHour(meridiemIndex, hourIndex),
      0,
    );

    // The end value of the range is exclusive, i.e. [rangeStart, rangeEnd).
    final DateTime rangeEnd = rangeStart.add(const Duration(hours: 1));

    return (widget.minimumDate?.isBefore(rangeEnd) ?? true)
        && !(widget.maximumDate?.isBefore(rangeStart) ?? false);
  }

745
  Widget _buildHourPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
746 747 748 749 750 751 752 753
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isHourPickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isHourPickerScrolling = false;
          _pickerDidStopScrolling();
        }
754

755 756 757 758 759 760 761 762 763 764 765 766 767
        return false;
      },
      child: CupertinoPicker(
        scrollController: hourController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: (int index) {
          final bool regionChanged = meridiemRegion != index ~/ 12;
          final bool debugIsFlipped = isHourRegionFlipped;
768

769 770 771 772
          if (regionChanged) {
            meridiemRegion = index ~/ 12;
            selectedAmPm = 1 - selectedAmPm;
          }
773

774 775 776 777 778
          if (!widget.use24hFormat && regionChanged) {
            // Scroll the meridiem column to adjust AM/PM.
            //
            // _onSelectedItemChanged will be called when the animation finishes.
            //
779
            // Animation values obtained by comparing with iOS version.
780 781
            meridiemController.animateToItem(
              selectedAmPm,
782
              duration: const Duration(milliseconds: 300),
783
              curve: Curves.easeOut,
784
            );
785
          } else {
786
            _onSelectedItemChange(index);
787
          }
788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
          assert(debugIsFlipped == isHourRegionFlipped);
        },
        children: List<Widget>.generate(24, (int index) {
          final int hour = isHourRegionFlipped ? (index + 12) % 24 : index;
          final int displayHour = widget.use24hFormat ? hour : (hour + 11) % 12 + 1;

          return itemPositioningBuilder(
            context,
            Text(
              localizations.datePickerHour(displayHour),
              semanticsLabel: localizations.datePickerHourSemanticsLabel(displayHour),
              style: _themeTextStyle(context, isValid: _isValidHour(selectedAmPm, index)),
            ),
          );
        }),
        looping: true,
805
        selectionOverlay: selectionOverlay,
806
      ),
807 808 809
    );
  }

810
  Widget _buildMinutePicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
811 812 813 814 815 816 817 818 819 820
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isMinutePickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isMinutePickerScrolling = false;
          _pickerDidStopScrolling();
        }

        return false;
821
      },
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
      child: CupertinoPicker(
        scrollController: minuteController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: _onSelectedItemChange,
        children: List<Widget>.generate(60 ~/ widget.minuteInterval, (int index) {
          final int minute = index * widget.minuteInterval;

          final DateTime date = DateTime(
            initialDateTime.year,
            initialDateTime.month,
            initialDateTime.day + selectedDayFromInitial,
            selectedHour,
            minute,
          );

          final bool isInvalidMinute = (widget.minimumDate?.isAfter(date) ?? false)
                                    || (widget.maximumDate?.isBefore(date) ?? false);

          return itemPositioningBuilder(
            context,
            Text(
              localizations.datePickerMinute(minute),
              semanticsLabel: localizations.datePickerMinuteSemanticsLabel(minute),
              style: _themeTextStyle(context, isValid: !isInvalidMinute),
            ),
          );
        }),
        looping: true,
855
        selectionOverlay: selectionOverlay,
856
      ),
857 858 859
    );
  }

860
  Widget _buildAmPmPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
861 862 863 864 865 866 867 868 869 870
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isMeridiemPickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isMeridiemPickerScrolling = false;
          _pickerDidStopScrolling();
        }

        return false;
871
      },
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
      child: CupertinoPicker(
        scrollController: meridiemController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: (int index) {
          selectedAmPm = index;
          assert(selectedAmPm == 0 || selectedAmPm == 1);
          _onSelectedItemChange(index);
        },
        children: List<Widget>.generate(2, (int index) {
          return itemPositioningBuilder(
            context,
            Text(
              index == 0
                ? localizations.anteMeridiemAbbreviation
                : localizations.postMeridiemAbbreviation,
              style: _themeTextStyle(context, isValid: _isValidHour(index, _selectedHourIndex)),
            ),
          );
        }),
896
        selectionOverlay: selectionOverlay,
897
      ),
898 899 900
    );
  }

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
  // One or more pickers have just stopped scrolling.
  void _pickerDidStopScrolling() {
    // Call setState to update the greyed out date/hour/minute/meridiem.
    setState(() { });

    if (isScrolling)
      return;

    // Whenever scrolling lands on an invalid entry, the picker
    // automatically scrolls to a valid one.
    final DateTime selectedDate = selectedDateTime;

    final bool minCheck = widget.minimumDate?.isAfter(selectedDate) ?? false;
    final bool maxCheck = widget.maximumDate?.isBefore(selectedDate) ?? false;

    if (minCheck || maxCheck) {
      // We have minCheck === !maxCheck.
918
      final DateTime targetDate = minCheck ? widget.minimumDate! : widget.maximumDate!;
919 920 921 922 923 924
      _scrollToDate(targetDate, selectedDate);
    }
  }

  void _scrollToDate(DateTime newDate, DateTime fromDate) {
    assert(newDate != null);
925
    SchedulerBinding.instance!.addPostFrameCallback((Duration timestamp) {
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
      if (fromDate.year != newDate.year || fromDate.month != newDate.month || fromDate.day != newDate.day) {
        _animateColumnControllerToItem(dateController, selectedDayFromInitial);
      }

      if (fromDate.hour != newDate.hour) {
        final bool needsMeridiemChange = !widget.use24hFormat
                                      && fromDate.hour ~/ 12 != newDate.hour ~/ 12;
        // In AM/PM mode, the pickers should not scroll all the way to the other hour region.
        if (needsMeridiemChange) {
          _animateColumnControllerToItem(meridiemController, 1 - meridiemController.selectedItem);

          // Keep the target item index in the current 12-h region.
          final int newItem = (hourController.selectedItem ~/ 12) * 12
                            + (hourController.selectedItem + newDate.hour - fromDate.hour) % 12;
          _animateColumnControllerToItem(hourController, newItem);
        } else {
          _animateColumnControllerToItem(
            hourController,
            hourController.selectedItem + newDate.hour - fromDate.hour,
          );
        }
      }

      if (fromDate.minute != newDate.minute) {
        _animateColumnControllerToItem(minuteController, newDate.minute);
      }
    });
  }

955 956 957 958 959 960 961
  @override
  Widget build(BuildContext context) {
    // Widths of the columns in this picker, ordered from left to right.
    final List<double> columnWidths = <double>[
      _getEstimatedColumnWidth(_PickerColumnType.hour),
      _getEstimatedColumnWidth(_PickerColumnType.minute),
    ];
962 963 964 965 966

    // Swap the hours and minutes if RTL to ensure they are in the correct position.
    final List<_ColumnBuilder> pickerBuilders = Directionality.of(context) == TextDirection.rtl
      ? <_ColumnBuilder>[_buildMinutePicker, _buildHourPicker]
      : <_ColumnBuilder>[_buildHourPicker, _buildMinutePicker];
967 968 969 970 971 972 973

    // Adds am/pm column if the picker is not using 24h format.
    if (!widget.use24hFormat) {
      if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.date_time_dayPeriod
        || localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date) {
        pickerBuilders.add(_buildAmPmPicker);
        columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
974
      } else {
975 976 977 978 979 980 981 982 983 984 985
        pickerBuilders.insert(0, _buildAmPmPicker);
        columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
      }
    }

    // Adds medium date column if the picker's mode is date and time.
    if (widget.mode == CupertinoDatePickerMode.dateAndTime) {
      if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date
          || localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.dayPeriod_time_date) {
        pickerBuilders.add(_buildMediumDatePicker);
        columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date));
986
      } else {
987 988 989 990 991 992
        pickerBuilders.insert(0, _buildMediumDatePicker);
        columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));
      }
    }

    final List<Widget> pickers = <Widget>[];
993

994 995
    for (int i = 0; i < columnWidths.length; i++) {
      double offAxisFraction = 0.0;
996 997
      Widget selectionOverlay = _centerSelectionOverlay;
      if (i == 0) {
998
        offAxisFraction = -_kMaximumOffAxisFraction * textDirectionFactor;
999 1000
        selectionOverlay = _leftSelectionOverlay;
      } else if (i >= 2 || columnWidths.length == 2)
1001
        offAxisFraction = _kMaximumOffAxisFraction * textDirectionFactor;
1002 1003

      EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);
1004
      if (i == columnWidths.length - 1) {
1005
        padding = padding.flipped;
1006 1007
        selectionOverlay = _rightSelectionOverlay;
      }
1008 1009 1010 1011 1012 1013 1014
      if (textDirectionFactor == -1)
        padding = padding.flipped;

      pickers.add(LayoutId(
        id: i,
        child: pickerBuilders[i](
          offAxisFraction,
1015
          (BuildContext context, Widget? child) {
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
            return Container(
              alignment: i == columnWidths.length - 1
                ? alignCenterLeft
                : alignCenterRight,
              padding: padding,
              child: Container(
                alignment: i == columnWidths.length - 1 ? alignCenterLeft : alignCenterRight,
                width: i == 0 || i == columnWidths.length - 1
                  ? null
                  : columnWidths[i] + _kDatePickerPadSize,
                child: child,
              ),
            );
          },
1030
          selectionOverlay,
1031 1032 1033 1034 1035
        ),
      ));
    }

    return MediaQuery(
1036
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
1037 1038 1039 1040 1041 1042 1043 1044
      child: DefaultTextStyle.merge(
        style: _kDefaultPickerTextStyle,
        child: CustomMultiChildLayout(
          delegate: _DatePickerLayoutDelegate(
            columnWidths: columnWidths,
            textDirectionFactor: textDirectionFactor,
          ),
          children: pickers,
1045 1046 1047 1048 1049 1050 1051
        ),
      ),
    );
  }
}

class _CupertinoDatePickerDateState extends State<CupertinoDatePicker> {
1052 1053
  late int textDirectionFactor;
  late CupertinoLocalizations localizations;
1054 1055 1056

  // Alignment based on text direction. The variable name is self descriptive,
  // however, when text direction is rtl, alignment is reversed.
1057 1058
  late Alignment alignCenterLeft;
  late Alignment alignCenterRight;
1059 1060

  // The currently selected values of the picker.
1061 1062 1063
  late int selectedDay;
  late int selectedMonth;
  late int selectedYear;
1064 1065 1066 1067

  // The controller of the day picker. There are cases where the selected value
  // of the picker is invalid (e.g. February 30th 2018), and this dayController
  // is responsible for jumping to a valid value.
1068 1069 1070
  late FixedExtentScrollController dayController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController yearController;
1071 1072 1073 1074 1075 1076

  bool isDayPickerScrolling = false;
  bool isMonthPickerScrolling = false;
  bool isYearPickerScrolling = false;

  bool get isScrolling => isDayPickerScrolling || isMonthPickerScrolling || isYearPickerScrolling;
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

  // Estimated width of columns.
  Map<int, double> estimatedColumnWidths = <int, double>{};

  @override
  void initState() {
    super.initState();
    selectedDay = widget.initialDateTime.day;
    selectedMonth = widget.initialDateTime.month;
    selectedYear = widget.initialDateTime.year;

    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
1089 1090
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    yearController = FixedExtentScrollController(initialItem: selectedYear);
1091

1092
    PaintingBinding.instance!.systemFonts.addListener(_handleSystemFontsChange);
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
  }

  void _handleSystemFontsChange() {
    setState(() {
      // System fonts change might cause the text layout width to change.
      _refreshEstimatedColumnWidths();
    });
  }

  @override
  void dispose() {
1104 1105 1106 1107
    dayController.dispose();
    monthController.dispose();
    yearController.dispose();

1108
    PaintingBinding.instance!.systemFonts.removeListener(_handleSystemFontsChange);
1109
    super.dispose();
1110 1111 1112 1113 1114 1115 1116
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    textDirectionFactor = Directionality.of(context) == TextDirection.ltr ? 1 : -1;
1117
    localizations = CupertinoLocalizations.of(context);
1118 1119 1120 1121

    alignCenterLeft = textDirectionFactor == 1 ? Alignment.centerLeft : Alignment.centerRight;
    alignCenterRight = textDirectionFactor == 1 ? Alignment.centerRight : Alignment.centerLeft;

1122 1123 1124 1125
    _refreshEstimatedColumnWidths();
  }

  void _refreshEstimatedColumnWidths() {
1126 1127 1128 1129 1130
    estimatedColumnWidths[_PickerColumnType.dayOfMonth.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.dayOfMonth, localizations, context);
    estimatedColumnWidths[_PickerColumnType.month.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.month, localizations, context);
    estimatedColumnWidths[_PickerColumnType.year.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.year, localizations, context);
  }

1131 1132 1133 1134
  // The DateTime of the last day of a given month in a given year.
  // Let `DateTime` handle the year/month overflow.
  DateTime _lastDayInMonth(int year, int month) => DateTime(year, month + 1, 0);

1135
  Widget _buildDayPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
1136 1137 1138 1139 1140 1141 1142 1143
    final int daysInCurrentMonth = _lastDayInMonth(selectedYear, selectedMonth).day;
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isDayPickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isDayPickerScrolling = false;
          _pickerDidStopScrolling();
1144
        }
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

        return false;
      },
      child: CupertinoPicker(
        scrollController: dayController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: (int index) {
          selectedDay = index + 1;
          if (_isCurrentDateValid)
            widget.onDateTimeChanged(DateTime(selectedYear, selectedMonth, selectedDay));
        },
        children: List<Widget>.generate(31, (int index) {
          final int day = index + 1;
          return itemPositioningBuilder(
            context,
            Text(
              localizations.datePickerDayOfMonth(day),
              style: _themeTextStyle(context, isValid: day <= daysInCurrentMonth),
            ),
          );
        }),
        looping: true,
1172
        selectionOverlay: selectionOverlay,
1173
      ),
1174 1175 1176
    );
  }

1177
  Widget _buildMonthPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isMonthPickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isMonthPickerScrolling = false;
          _pickerDidStopScrolling();
        }

        return false;
1188
      },
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
      child: CupertinoPicker(
        scrollController: monthController,
        offAxisFraction: offAxisFraction,
        itemExtent: _kItemExtent,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        squeeze: _kSqueeze,
        onSelectedItemChanged: (int index) {
          selectedMonth = index + 1;
          if (_isCurrentDateValid)
            widget.onDateTimeChanged(DateTime(selectedYear, selectedMonth, selectedDay));
        },
        children: List<Widget>.generate(12, (int index) {
          final int month = index + 1;
1204 1205
          final bool isInvalidMonth = (widget.minimumDate?.year == selectedYear && widget.minimumDate!.month > month)
                                   || (widget.maximumDate?.year == selectedYear && widget.maximumDate!.month < month);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

          return itemPositioningBuilder(
            context,
            Text(
              localizations.datePickerMonth(month),
              style: _themeTextStyle(context, isValid: !isInvalidMonth),
            ),
          );
        }),
        looping: true,
1216
        selectionOverlay: selectionOverlay,
1217
      ),
1218 1219 1220
    );
  }

1221
  Widget _buildYearPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {
1222 1223 1224 1225 1226 1227 1228 1229
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification) {
          isYearPickerScrolling = true;
        } else if (notification is ScrollEndNotification) {
          isYearPickerScrolling = false;
          _pickerDidStopScrolling();
        }
1230

1231
        return false;
1232
      },
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
      child: CupertinoPicker.builder(
        scrollController: yearController,
        itemExtent: _kItemExtent,
        offAxisFraction: offAxisFraction,
        useMagnifier: _kUseMagnifier,
        magnification: _kMagnification,
        backgroundColor: widget.backgroundColor,
        onSelectedItemChanged: (int index) {
          selectedYear = index;
          if (_isCurrentDateValid)
            widget.onDateTimeChanged(DateTime(selectedYear, selectedMonth, selectedDay));
        },
        itemBuilder: (BuildContext context, int year) {
          if (year < widget.minimumYear)
            return null;

1249
          if (widget.maximumYear != null && year > widget.maximumYear!)
1250 1251
            return null;

1252 1253
          final bool isValidYear = (widget.minimumDate == null || widget.minimumDate!.year <= year)
                                && (widget.maximumDate == null || widget.maximumDate!.year >= year);
1254 1255 1256 1257 1258 1259 1260 1261 1262

          return itemPositioningBuilder(
            context,
            Text(
              localizations.datePickerYear(year),
              style: _themeTextStyle(context, isValid: isValidYear),
            ),
          );
        },
1263
        selectionOverlay: selectionOverlay,
1264
      ),
1265 1266 1267
    );
  }

1268
  bool get _isCurrentDateValid {
1269 1270 1271
    // The current date selection represents a range [minSelectedData, maxSelectDate].
    final DateTime minSelectedDate = DateTime(selectedYear, selectedMonth, selectedDay);
    final DateTime maxSelectedDate = DateTime(selectedYear, selectedMonth, selectedDay + 1);
1272

1273 1274
    final bool minCheck = widget.minimumDate?.isBefore(maxSelectedDate) ?? true;
    final bool maxCheck = widget.maximumDate?.isBefore(minSelectedDate) ?? false;
1275

1276
    return minCheck && !maxCheck && minSelectedDate.day == selectedDay;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  }

  // One or more pickers have just stopped scrolling.
  void _pickerDidStopScrolling() {
    // Call setState to update the greyed out days/months/years, as the currently
    // selected year/month may have changed.
    setState(() { });

    if (isScrolling) {
      return;
    }

1289 1290
    // Whenever scrolling lands on an invalid entry, the picker
    // automatically scrolls to a valid one.
1291 1292
    final DateTime minSelectDate = DateTime(selectedYear, selectedMonth, selectedDay);
    final DateTime maxSelectDate = DateTime(selectedYear, selectedMonth, selectedDay + 1);
1293

1294 1295
    final bool minCheck = widget.minimumDate?.isBefore(maxSelectDate) ?? true;
    final bool maxCheck = widget.maximumDate?.isBefore(minSelectDate) ?? false;
1296

1297
    if (!minCheck || maxCheck) {
1298
      // We have minCheck === !maxCheck.
1299
      final DateTime targetDate = minCheck ? widget.maximumDate! : widget.minimumDate!;
1300 1301 1302 1303 1304 1305
      _scrollToDate(targetDate);
      return;
    }

    // Some months have less days (e.g. February). Go to the last day of that month
    // if the selectedDay exceeds the maximum.
1306
    if (minSelectDate.day != selectedDay) {
1307 1308 1309 1310 1311 1312 1313
      final DateTime lastDay = _lastDayInMonth(selectedYear, selectedMonth);
      _scrollToDate(lastDay);
    }
  }

  void _scrollToDate(DateTime newDate) {
    assert(newDate != null);
1314
    SchedulerBinding.instance!.addPostFrameCallback((Duration timestamp) {
1315
      if (selectedYear != newDate.year) {
1316
        _animateColumnControllerToItem(yearController, newDate.year);
1317 1318 1319
      }

      if (selectedMonth != newDate.month) {
1320
        _animateColumnControllerToItem(monthController, newDate.month - 1);
1321 1322 1323
      }

      if (selectedDay != newDate.day) {
1324
        _animateColumnControllerToItem(dayController, newDate.day - 1);
1325
      }
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    });
  }

  @override
  Widget build(BuildContext context) {
    List<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[];
    List<double> columnWidths = <double>[];

    switch (localizations.datePickerDateOrder) {
      case DatePickerDateOrder.mdy:
        pickerBuilders = <_ColumnBuilder>[_buildMonthPicker, _buildDayPicker, _buildYearPicker];
        columnWidths = <double>[
1338 1339 1340 1341
          estimatedColumnWidths[_PickerColumnType.month.index]!,
          estimatedColumnWidths[_PickerColumnType.dayOfMonth.index]!,
          estimatedColumnWidths[_PickerColumnType.year.index]!,
        ];
1342 1343 1344 1345
        break;
      case DatePickerDateOrder.dmy:
        pickerBuilders = <_ColumnBuilder>[_buildDayPicker, _buildMonthPicker, _buildYearPicker];
        columnWidths = <double>[
1346 1347 1348 1349
          estimatedColumnWidths[_PickerColumnType.dayOfMonth.index]!,
          estimatedColumnWidths[_PickerColumnType.month.index]!,
          estimatedColumnWidths[_PickerColumnType.year.index]!,
        ];
1350 1351 1352 1353
        break;
      case DatePickerDateOrder.ymd:
        pickerBuilders = <_ColumnBuilder>[_buildYearPicker, _buildMonthPicker, _buildDayPicker];
        columnWidths = <double>[
1354 1355 1356 1357
          estimatedColumnWidths[_PickerColumnType.year.index]!,
          estimatedColumnWidths[_PickerColumnType.month.index]!,
          estimatedColumnWidths[_PickerColumnType.dayOfMonth.index]!,
        ];
1358 1359 1360 1361
        break;
      case DatePickerDateOrder.ydm:
        pickerBuilders = <_ColumnBuilder>[_buildYearPicker, _buildDayPicker, _buildMonthPicker];
        columnWidths = <double>[
1362 1363 1364 1365
          estimatedColumnWidths[_PickerColumnType.year.index]!,
          estimatedColumnWidths[_PickerColumnType.dayOfMonth.index]!,
          estimatedColumnWidths[_PickerColumnType.month.index]!,
        ];
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
        break;
    }

    final List<Widget> pickers = <Widget>[];

    for (int i = 0; i < columnWidths.length; i++) {
      final double offAxisFraction = (i - 1) * 0.3 * textDirectionFactor;

      EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);
      if (textDirectionFactor == -1)
        padding = const EdgeInsets.only(left: _kDatePickerPadSize);

1378 1379 1380 1381 1382 1383
      Widget selectionOverlay = _centerSelectionOverlay;
      if (i == 0)
        selectionOverlay = _leftSelectionOverlay;
      else if (i == columnWidths.length - 1)
        selectionOverlay = _rightSelectionOverlay;

1384 1385 1386 1387
      pickers.add(LayoutId(
        id: i,
        child: pickerBuilders[i](
          offAxisFraction,
1388
          (BuildContext context, Widget? child) {
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
            return Container(
              alignment: i == columnWidths.length - 1
                  ? alignCenterLeft
                  : alignCenterRight,
              padding: i == 0 ? null : padding,
              child: Container(
                alignment: i == 0 ? alignCenterLeft : alignCenterRight,
                width: columnWidths[i] + _kDatePickerPadSize,
                child: child,
              ),
            );
          },
1401
          selectionOverlay,
1402 1403 1404 1405 1406
        ),
      ));
    }

    return MediaQuery(
1407
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
1408 1409 1410 1411 1412 1413
      child: DefaultTextStyle.merge(
        style: _kDefaultPickerTextStyle,
        child: CustomMultiChildLayout(
          delegate: _DatePickerLayoutDelegate(
            columnWidths: columnWidths,
            textDirectionFactor: textDirectionFactor,
1414
          ),
1415
          children: pickers,
1416 1417 1418 1419 1420 1421 1422
        ),
      ),
    );
  }
}


1423 1424 1425
// The iOS date picker and timer picker has their width fixed to 320.0 in all
// modes. The only exception is the hms mode (which doesn't have a native counterpart),
// with a fixed width of 330.0 px.
1426
//
1427 1428 1429
// For date pickers, if the maximum width given to the picker is greater than
// 320.0, the leftmost and rightmost column will be extended equally so that the
// widths match, and the picker is in the center.
1430
//
1431 1432 1433 1434 1435
// For timer pickers, if the maximum width given to the picker is greater than
// its intrinsic width, it will keep its intrinsic size and position itself in the
// parent using its alignment parameter.
//
// If the maximum width given to the picker is smaller than 320.0, the picker's
1436
// layout will be broken.
1437 1438 1439


/// Different modes of [CupertinoTimerPicker].
1440 1441 1442 1443 1444
///
/// See also:
///
///  * [CupertinoTimerPicker], the class that implements the iOS-style timer picker.
///  * [CupertinoPicker], the class that implements a content agnostic spinner UI.
1445 1446 1447
enum CupertinoTimerPickerMode {
  /// Mode that shows the timer duration in hour and minute.
  ///
1448
  /// Examples: 16 hours | 14 min.
1449 1450 1451
  hm,
  /// Mode that shows the timer duration in minute and second.
  ///
1452
  /// Examples: 14 min | 43 sec.
1453 1454 1455
  ms,
  /// Mode that shows the timer duration in hour, minute, and second.
  ///
1456
  /// Examples: 16 hours | 14 min | 43 sec.
1457 1458 1459 1460 1461 1462 1463 1464 1465
  hms,
}

/// A countdown timer picker in iOS style.
///
/// This picker shows a countdown duration with hour, minute and second spinners.
/// The duration is bound between 0 and 23 hours 59 minutes 59 seconds.
///
/// There are several modes of the timer picker listed in [CupertinoTimerPickerMode].
1466
///
1467 1468 1469 1470
/// The picker has a fixed size of 320 x 216, in logical pixels, with the exception
/// of [CupertinoTimerPickerMode.hms], which is 330 x 216. If the parent widget
/// provides more space than it needs, the picker will position itself according
/// to its [alignment] property.
1471
///
1472 1473 1474
/// See also:
///
///  * [CupertinoDatePicker], the class that implements different display modes
1475
///    of the iOS-style date picker.
1476
///  * [CupertinoPicker], the class that implements a content agnostic spinner UI.
1477 1478 1479 1480 1481 1482
class CupertinoTimerPicker extends StatefulWidget {
  /// Constructs an iOS style countdown timer picker.
  ///
  /// [mode] is one of the modes listed in [CupertinoTimerPickerMode] and
  /// defaults to [CupertinoTimerPickerMode.hms].
  ///
1483 1484
  /// [onTimerDurationChanged] is the callback called when the selected duration
  /// changes and must not be null.
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
  ///
  /// [initialTimerDuration] defaults to 0 second and is limited from 0 second
  /// to 23 hours 59 minutes 59 seconds.
  ///
  /// [minuteInterval] is the granularity of the minute spinner. Must be a
  /// positive integer factor of 60.
  ///
  /// [secondInterval] is the granularity of the second spinner. Must be a
  /// positive integer factor of 60.
  CupertinoTimerPicker({
1495
    Key? key,
1496
    this.mode = CupertinoTimerPickerMode.hms,
1497
    this.initialTimerDuration = Duration.zero,
1498 1499
    this.minuteInterval = 1,
    this.secondInterval = 1,
1500
    this.alignment = Alignment.center,
1501
    this.backgroundColor,
1502
    required this.onTimerDurationChanged,
1503 1504
  }) : assert(mode != null),
       assert(onTimerDurationChanged != null),
1505
       assert(initialTimerDuration >= Duration.zero),
1506 1507 1508 1509
       assert(initialTimerDuration < const Duration(days: 1)),
       assert(minuteInterval > 0 && 60 % minuteInterval == 0),
       assert(secondInterval > 0 && 60 % secondInterval == 0),
       assert(initialTimerDuration.inMinutes % minuteInterval == 0),
1510
       assert(initialTimerDuration.inSeconds % secondInterval == 0),
1511 1512
       assert(alignment != null),
       super(key: key);
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527

  /// The mode of the timer picker.
  final CupertinoTimerPickerMode mode;

  /// The initial duration of the countdown timer.
  final Duration initialTimerDuration;

  /// The granularity of the minute spinner. Must be a positive integer factor
  /// of 60.
  final int minuteInterval;

  /// The granularity of the second spinner. Must be a positive integer factor
  /// of 60.
  final int secondInterval;

1528
  /// Callback called when the timer duration changes.
1529 1530
  final ValueChanged<Duration> onTimerDurationChanged;

1531
  /// Defines how the timer picker should be positioned within its parent.
1532 1533 1534 1535
  ///
  /// This property must not be null. It defaults to [Alignment.center].
  final AlignmentGeometry alignment;

1536 1537
  /// Background color of timer picker.
  ///
1538
  /// Defaults to null, which disables background painting entirely.
1539
  final Color? backgroundColor;
1540

1541
  @override
1542
  State<StatefulWidget> createState() => _CupertinoTimerPickerState();
1543 1544 1545
}

class _CupertinoTimerPickerState extends State<CupertinoTimerPicker> {
1546 1547
  late TextDirection textDirection;
  late CupertinoLocalizations localizations;
1548 1549 1550 1551 1552 1553 1554 1555
  int get textDirectionFactor {
    switch (textDirection) {
      case TextDirection.ltr:
        return 1;
      case TextDirection.rtl:
        return -1;
    }
  }
1556 1557

  // The currently selected values of the picker.
1558 1559 1560
  int? selectedHour;
  late int selectedMinute;
  int? selectedSecond;
1561

1562 1563
  // On iOS the selected values won't be reported until the scrolling fully stops.
  // The values below are the latest selected values when the picker comes to a full stop.
1564 1565 1566
  int? lastSelectedHour;
  int? lastSelectedMinute;
  int? lastSelectedSecond;
1567 1568 1569

  final TextPainter textPainter = TextPainter();
  final List<String> numbers = List<String>.generate(10, (int i) => '${9 - i}');
1570 1571 1572
  late double numberLabelWidth;
  late double numberLabelHeight;
  late double numberLabelBaseline;
1573

1574 1575 1576 1577 1578 1579 1580
  late double hourLabelWidth;
  late double minuteLabelWidth;
  late double secondLabelWidth;

  late double totalWidth;
  late double pickerColumnWidth;

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  @override
  void initState() {
    super.initState();

    selectedMinute = widget.initialTimerDuration.inMinutes % 60;

    if (widget.mode != CupertinoTimerPickerMode.ms)
      selectedHour = widget.initialTimerDuration.inHours;

    if (widget.mode != CupertinoTimerPickerMode.hm)
      selectedSecond = widget.initialTimerDuration.inSeconds % 60;
1592

1593
    PaintingBinding.instance!.systemFonts.addListener(_handleSystemFontsChange);
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
  }

  void _handleSystemFontsChange() {
    setState(() {
      // System fonts change might cause the text layout width to change.
      textPainter.markNeedsLayout();
      _measureLabelMetrics();
    });
  }

  @override
  void dispose() {
1606
    PaintingBinding.instance!.systemFonts.removeListener(_handleSystemFontsChange);
1607
    super.dispose();
1608 1609
  }

1610 1611 1612 1613 1614 1615 1616
  @override
  void didUpdateWidget(CupertinoTimerPicker oldWidget) {
    super.didUpdateWidget(oldWidget);

    assert(
      oldWidget.mode == widget.mode,
      "The CupertinoTimerPicker's mode cannot change once it's built",
1617 1618 1619 1620 1621 1622 1623
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

1624
    textDirection = Directionality.of(context);
1625
    localizations = CupertinoLocalizations.of(context);
1626

1627 1628 1629 1630
    _measureLabelMetrics();
  }

  void _measureLabelMetrics() {
1631
    textPainter.textDirection = textDirection;
1632
    final TextStyle textStyle = _textStyleFrom(context, _kTimerPickerMagnification);
1633 1634

    double maxWidth = double.negativeInfinity;
1635
    String? widestNumber;
1636 1637 1638 1639 1640 1641 1642 1643

    // Assumes that:
    // - 2-digit numbers are always wider than 1-digit numbers.
    // - There's at least one number in 1-9 that's wider than or equal to 0.
    // - The widest 2-digit number is composed of 2 same 1-digit numbers
    //   that has the biggest width.
    // - If two different 1-digit numbers are of the same width, their corresponding
    //   2 digit numbers are of the same width.
1644
    for (final String input in numbers) {
1645 1646
      textPainter.text = TextSpan(
        text: input,
1647
        style: textStyle,
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
      );
      textPainter.layout();

      if (textPainter.maxIntrinsicWidth > maxWidth) {
        maxWidth = textPainter.maxIntrinsicWidth;
        widestNumber = input;
      }
    }

    textPainter.text = TextSpan(
      text: '$widestNumber$widestNumber',
1659
      style: textStyle,
1660 1661 1662 1663 1664 1665
    );

    textPainter.layout();
    numberLabelWidth = textPainter.maxIntrinsicWidth;
    numberLabelHeight = textPainter.height;
    numberLabelBaseline = textPainter.computeDistanceToActualBaseline(TextBaseline.alphabetic);
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

    minuteLabelWidth =
        _measureLabelsMaxWidth(localizations.timerPickerMinuteLabels, textStyle);

    if (widget.mode != CupertinoTimerPickerMode.ms)
      hourLabelWidth =
          _measureLabelsMaxWidth(localizations.timerPickerHourLabels, textStyle);

    if (widget.mode != CupertinoTimerPickerMode.hm)
      secondLabelWidth =
          _measureLabelsMaxWidth(localizations.timerPickerSecondLabels, textStyle);
  }

  // Measures all possible time text labels and return maximum width.
  double _measureLabelsMaxWidth(List<String?> labels, TextStyle style) {
    double maxWidth = double.negativeInfinity;
    for (int i = 0; i < labels.length; i++) {
      final String? label = labels[i];
      if(label == null) {
        continue;
      }

      textPainter.text = TextSpan(text: label, style: style);
      textPainter.layout();
      textPainter.maxIntrinsicWidth;
      if (textPainter.maxIntrinsicWidth > maxWidth)
        maxWidth = textPainter.maxIntrinsicWidth;
    }

    return maxWidth;
1696 1697
  }

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  // Builds a text label with scale factor 1.0 and font weight semi-bold.
  // `pickerPadding ` is the additional padding the corresponding picker has to apply
  // around the `Text`, in order to extend its separators towards the closest
  // horizontal edge of the encompassing widget.
  Widget _buildLabel(String text, EdgeInsetsDirectional pickerPadding) {
    final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
      start: numberLabelWidth
           + _kTimerPickerLabelPadSize
           + pickerPadding.start,
    );

    return IgnorePointer(
      child: Container(
        alignment: AlignmentDirectional.centerStart.resolve(textDirection),
        padding: padding.resolve(textDirection),
        child: SizedBox(
          height: numberLabelHeight,
          child: Baseline(
            baseline: numberLabelBaseline,
            baselineType: TextBaseline.alphabetic,
            child: Text(
              text,
              style: const TextStyle(
                fontSize: _kTimerPickerLabelFontSize,
1722
                fontWeight: FontWeight.w600,
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
              ),
              maxLines: 1,
              softWrap: false,
            ),
          ),
        ),
      ),
    );
  }

  // The picker has to be wider than its content, since the separators
  // are part of the picker.
  Widget _buildPickerNumberLabel(String text, EdgeInsetsDirectional padding) {
    return Container(
      width: _kTimerPickerColumnIntrinsicWidth + padding.horizontal,
      padding: padding.resolve(textDirection),
      alignment: AlignmentDirectional.centerStart.resolve(textDirection),
      child: Container(
        width: numberLabelWidth,
        alignment: AlignmentDirectional.centerEnd.resolve(textDirection),
        child: Text(text, softWrap: false, maxLines: 1, overflow: TextOverflow.visible),
      ),
    );
  }

1748
  Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
1749
    return CupertinoPicker(
1750
      scrollController: FixedExtentScrollController(initialItem: selectedHour!),
1751 1752
      magnification: _kMagnification,
      offAxisFraction: _calculateOffAxisFraction(additionalPadding.start, 0),
1753
      itemExtent: _kItemExtent,
1754
      backgroundColor: widget.backgroundColor,
1755
      squeeze: _kSqueeze,
1756 1757 1758 1759
      onSelectedItemChanged: (int index) {
        setState(() {
          selectedHour = index;
          widget.onTimerDurationChanged(
1760 1761 1762 1763 1764 1765
            Duration(
              hours: selectedHour!,
              minutes: selectedMinute,
              seconds: selectedSecond ?? 0,
            ),
          );
1766 1767
        });
      },
1768
      children: List<Widget>.generate(24, (int index) {
1769
        final String label = localizations.timerPickerHourLabel(index) ?? '';
1770
        final String semanticsLabel = textDirectionFactor == 1
1771 1772
            ? localizations.timerPickerHour(index) + label
            : label + localizations.timerPickerHour(index);
1773

1774
        return Semantics(
1775
          label: semanticsLabel,
1776
          excludeSemantics: true,
1777
          child: _buildPickerNumberLabel(localizations.timerPickerHour(index), additionalPadding),
1778 1779
        );
      }),
1780
      selectionOverlay: selectionOverlay,
1781 1782 1783
    );
  }

1784 1785 1786 1787 1788 1789
  Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
    additionalPadding = EdgeInsetsDirectional.only(
      start: math.max(additionalPadding.start, 0),
      end: math.max(additionalPadding.end, 0),
    );

1790
    return Stack(
1791
      children: <Widget>[
1792 1793 1794 1795 1796
        NotificationListener<ScrollEndNotification>(
          onNotification: (ScrollEndNotification notification) {
            setState(() { lastSelectedHour = selectedHour; });
            return false;
          },
1797
          child: _buildHourPicker(additionalPadding, selectionOverlay),
1798 1799
        ),
        _buildLabel(
1800
          localizations.timerPickerHourLabel(lastSelectedHour ?? selectedHour!) ?? '',
1801
          additionalPadding,
1802
        ),
1803 1804 1805 1806
      ],
    );
  }

1807
  Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
1808 1809
    return CupertinoPicker(
      scrollController: FixedExtentScrollController(
1810 1811
        initialItem: selectedMinute ~/ widget.minuteInterval,
      ),
1812 1813 1814
      magnification: _kMagnification,
      offAxisFraction: _calculateOffAxisFraction(
          additionalPadding.start,
1815
          widget.mode == CupertinoTimerPickerMode.ms ? 0 : 1,
1816
      ),
1817
      itemExtent: _kItemExtent,
1818
      backgroundColor: widget.backgroundColor,
1819
      squeeze: _kSqueeze,
1820
      looping: true,
1821 1822
      onSelectedItemChanged: (int index) {
        setState(() {
1823
          selectedMinute = index * widget.minuteInterval;
1824
          widget.onTimerDurationChanged(
1825 1826 1827 1828 1829 1830
            Duration(
              hours: selectedHour ?? 0,
              minutes: selectedMinute,
              seconds: selectedSecond ?? 0,
            ),
          );
1831 1832
        });
      },
1833
      children: List<Widget>.generate(60 ~/ widget.minuteInterval, (int index) {
1834
        final int minute = index * widget.minuteInterval;
1835
        final String label = localizations.timerPickerMinuteLabel(minute) ?? '';
1836
        final String semanticsLabel = textDirectionFactor == 1
1837 1838
            ? localizations.timerPickerMinute(minute) + label
            : label + localizations.timerPickerMinute(minute);
1839

1840 1841 1842 1843 1844
        return Semantics(
          label: semanticsLabel,
          excludeSemantics: true,
          child: _buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding),
        );
1845
      }),
1846
      selectionOverlay: selectionOverlay,
1847 1848 1849
    );
  }

1850 1851 1852 1853 1854 1855
  Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
    additionalPadding = EdgeInsetsDirectional.only(
      start: math.max(additionalPadding.start, 0),
      end: math.max(additionalPadding.end, 0),
    );

1856 1857
    return Stack(
      children: <Widget>[
1858 1859 1860 1861 1862
        NotificationListener<ScrollEndNotification>(
          onNotification: (ScrollEndNotification notification) {
            setState(() { lastSelectedMinute = selectedMinute; });
            return false;
          },
1863
          child: _buildMinutePicker(additionalPadding, selectionOverlay),
1864 1865
        ),
        _buildLabel(
1866
          localizations.timerPickerMinuteLabel(lastSelectedMinute ?? selectedMinute) ?? '',
1867 1868
          additionalPadding,
        ),
1869 1870 1871 1872
      ],
    );
  }

1873
  Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
1874 1875
    return CupertinoPicker(
      scrollController: FixedExtentScrollController(
1876
        initialItem: selectedSecond! ~/ widget.secondInterval,
1877
      ),
1878 1879 1880
      magnification: _kMagnification,
      offAxisFraction: _calculateOffAxisFraction(
          additionalPadding.start,
1881
          widget.mode == CupertinoTimerPickerMode.ms ? 1 : 2,
1882
      ),
1883
      itemExtent: _kItemExtent,
1884
      backgroundColor: widget.backgroundColor,
1885
      squeeze: _kSqueeze,
1886
      looping: true,
1887 1888
      onSelectedItemChanged: (int index) {
        setState(() {
1889
          selectedSecond = index * widget.secondInterval;
1890
          widget.onTimerDurationChanged(
1891 1892 1893 1894 1895 1896
            Duration(
              hours: selectedHour ?? 0,
              minutes: selectedMinute,
              seconds: selectedSecond!,
            ),
          );
1897 1898
        });
      },
1899
      children: List<Widget>.generate(60 ~/ widget.secondInterval, (int index) {
1900
        final int second = index * widget.secondInterval;
1901
        final String label = localizations.timerPickerSecondLabel(second) ?? '';
1902
        final String semanticsLabel = textDirectionFactor == 1
1903 1904
            ? localizations.timerPickerSecond(second) + label
            : label + localizations.timerPickerSecond(second);
1905

1906
        return Semantics(
1907
          label: semanticsLabel,
1908
          excludeSemantics: true,
1909
          child: _buildPickerNumberLabel(localizations.timerPickerSecond(second), additionalPadding),
1910 1911
        );
      }),
1912
      selectionOverlay: selectionOverlay,
1913 1914 1915
    );
  }

1916 1917 1918 1919 1920 1921
  Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {
    additionalPadding = EdgeInsetsDirectional.only(
      start: math.max(additionalPadding.start, 0),
      end: math.max(additionalPadding.end, 0),
    );

1922 1923
    return Stack(
      children: <Widget>[
1924 1925 1926 1927 1928
        NotificationListener<ScrollEndNotification>(
          onNotification: (ScrollEndNotification notification) {
            setState(() { lastSelectedSecond = selectedSecond; });
            return false;
          },
1929
          child: _buildSecondPicker(additionalPadding, selectionOverlay),
1930 1931
        ),
        _buildLabel(
1932
          localizations.timerPickerSecondLabel(lastSelectedSecond ?? selectedSecond!) ?? '',
1933 1934
          additionalPadding,
        ),
1935 1936 1937 1938
      ],
    );
  }

1939 1940 1941 1942 1943
  // Returns [CupertinoTextThemeData.pickerTextStyle] and magnifies the fontSize
  // by [magnification].
  TextStyle _textStyleFrom(BuildContext context, [double magnification = 1.0]) {
    final TextStyle textStyle = CupertinoTheme.of(context).textTheme.pickerTextStyle;
    return textStyle.copyWith(
1944
      fontSize: textStyle.fontSize! * magnification,
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
    );
  }

  // Calculate the number label center point by padding start and position to
  // get a reasonable offAxisFraction.
  double _calculateOffAxisFraction(double paddingStart, int position) {
    final double centerPoint = paddingStart + (numberLabelWidth / 2);

    // Compute the offAxisFraction needed to be straight within the pickerColumn.
    final double pickerColumnOffAxisFraction =
        0.5 - centerPoint / pickerColumnWidth;
    // Position is to calculate the reasonable offAxisFraction in the picker.
    final double timerPickerOffAxisFraction =
        0.5 - (centerPoint + pickerColumnWidth * position) / totalWidth;
    return (pickerColumnOffAxisFraction - timerPickerOffAxisFraction) * textDirectionFactor;
1960 1961
  }

1962 1963
  @override
  Widget build(BuildContext context) {
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        // The timer picker can be divided into columns corresponding to hour,
        // minute, and second. Each column consists of a scrollable and a fixed
        // label on top of it.
        List<Widget> columns;

        if (widget.mode == CupertinoTimerPickerMode.hms){
          // Pad the widget to make it as wide as `_kPickerWidth`.
          pickerColumnWidth =
              _kTimerPickerColumnIntrinsicWidth + (_kTimerPickerHalfColumnPadding * 2);
          totalWidth = pickerColumnWidth * 3;
        } else {
          // The default totalWidth for 2-column modes.
          totalWidth = _kPickerWidth;
          pickerColumnWidth = totalWidth / 2;
        }
1981

1982 1983 1984 1985 1986
        if (constraints.maxWidth < totalWidth) {
          totalWidth = constraints.maxWidth;
          pickerColumnWidth =
              totalWidth / (widget.mode == CupertinoTimerPickerMode.hms ? 3 : 2);
        }
1987

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
        final double baseLabelContentWidth = numberLabelWidth + _kTimerPickerLabelPadSize;
        final double minuteLabelContentWidth = baseLabelContentWidth + minuteLabelWidth;

        switch (widget.mode) {
          case CupertinoTimerPickerMode.hm:
          // Pad the widget to make it as wide as `_kPickerWidth`.
            final double hourLabelContentWidth = baseLabelContentWidth + hourLabelWidth;
            double hourColumnStartPadding =
                pickerColumnWidth - hourLabelContentWidth - _kTimerPickerHalfColumnPadding;
            if (hourColumnStartPadding < _kTimerPickerMinHorizontalPadding)
              hourColumnStartPadding = _kTimerPickerMinHorizontalPadding;

            double minuteColumnEndPadding =
                pickerColumnWidth - minuteLabelContentWidth - _kTimerPickerHalfColumnPadding;
            if (minuteColumnEndPadding < _kTimerPickerMinHorizontalPadding)
              minuteColumnEndPadding = _kTimerPickerMinHorizontalPadding;

            columns = <Widget>[
              _buildHourColumn(
                  EdgeInsetsDirectional.only(
                      start: hourColumnStartPadding,
2009
                      end: pickerColumnWidth - hourColumnStartPadding - hourLabelContentWidth,
2010
                  ),
2011
                  _leftSelectionOverlay,
2012 2013 2014 2015
              ),
              _buildMinuteColumn(
                  EdgeInsetsDirectional.only(
                      start: pickerColumnWidth - minuteColumnEndPadding - minuteLabelContentWidth,
2016
                      end: minuteColumnEndPadding,
2017
                  ),
2018
                  _rightSelectionOverlay,
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
              ),
            ];
            break;
          case CupertinoTimerPickerMode.ms:
            final double secondLabelContentWidth = baseLabelContentWidth + secondLabelWidth;
            double secondColumnEndPadding =
                pickerColumnWidth - secondLabelContentWidth - _kTimerPickerHalfColumnPadding;
            if (secondColumnEndPadding < _kTimerPickerMinHorizontalPadding)
              secondColumnEndPadding = _kTimerPickerMinHorizontalPadding;

            double minuteColumnStartPadding =
                pickerColumnWidth - minuteLabelContentWidth - _kTimerPickerHalfColumnPadding;
            if (minuteColumnStartPadding < _kTimerPickerMinHorizontalPadding)
              minuteColumnStartPadding = _kTimerPickerMinHorizontalPadding;

            columns = <Widget>[
              _buildMinuteColumn(
                  EdgeInsetsDirectional.only(
                      start: minuteColumnStartPadding,
2038
                      end: pickerColumnWidth - minuteColumnStartPadding - minuteLabelContentWidth,
2039
                  ),
2040
                  _leftSelectionOverlay,
2041 2042 2043 2044
              ),
              _buildSecondColumn(
                  EdgeInsetsDirectional.only(
                      start: pickerColumnWidth - secondColumnEndPadding - minuteLabelContentWidth,
2045
                      end: secondColumnEndPadding,
2046
                  ),
2047
                  _rightSelectionOverlay,
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
              ),
            ];
            break;
          case CupertinoTimerPickerMode.hms:
            final double hourColumnEndPadding =
                pickerColumnWidth - baseLabelContentWidth - hourLabelWidth - _kTimerPickerMinHorizontalPadding;
            final double minuteColumnPadding =
                (pickerColumnWidth - minuteLabelContentWidth) / 2;
            final double secondColumnStartPadding =
                pickerColumnWidth - baseLabelContentWidth - secondLabelWidth - _kTimerPickerMinHorizontalPadding;

            columns = <Widget>[
              _buildHourColumn(
                  EdgeInsetsDirectional.only(
                      start: _kTimerPickerMinHorizontalPadding,
2063
                      end: math.max(hourColumnEndPadding, 0),
2064
                  ),
2065
                  _leftSelectionOverlay,
2066 2067 2068 2069
              ),
              _buildMinuteColumn(
                  EdgeInsetsDirectional.only(
                      start: minuteColumnPadding,
2070
                      end: minuteColumnPadding,
2071
                  ),
2072
                  _centerSelectionOverlay,
2073 2074 2075 2076
              ),
              _buildSecondColumn(
                  EdgeInsetsDirectional.only(
                      start: math.max(secondColumnStartPadding, 0),
2077
                      end: _kTimerPickerMinHorizontalPadding,
2078
                  ),
2079
                  _rightSelectionOverlay,
2080 2081 2082 2083 2084 2085 2086 2087
              ),
            ];
            break;
        }
        final CupertinoThemeData themeData = CupertinoTheme.of(context);
        return MediaQuery(
          // The native iOS picker's text scaling is fixed, so we will also fix it
          // as well in our picker.
2088
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
2089 2090 2091 2092 2093 2094 2095 2096 2097
          child: CupertinoTheme(
            data: themeData.copyWith(
              textTheme: themeData.textTheme.copyWith(
                pickerTextStyle: _textStyleFrom(context, _kTimerPickerMagnification),
              ),
            ),
            child: Align(
              alignment: widget.alignment,
              child: Container(
2098
                color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context),
2099 2100 2101 2102 2103 2104 2105
                width: totalWidth,
                height: _kPickerHeight,
                child: DefaultTextStyle(
                  style: _textStyleFrom(context),
                  child: Row(children: columns.map((Widget child) => Expanded(child: child)).toList(growable: false)),
                ),
              ),
2106 2107
            ),
          ),
2108 2109
        );
      },
2110 2111
    );
  }
2112
}