Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- flutter/packages/flutter/lib/fix_data/README.md+1-2
- flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml+135-2
- flutter/packages/flutter/lib/fix_data/fix_gestures.yaml+1-1
- flutter/packages/flutter/lib/fix_data/fix_painting.yaml+46-1
- flutter/packages/flutter/lib/fix_data/fix_rendering.yaml+3-3
- flutter/packages/flutter/lib/fix_data/fix_services.yaml+15-1
- flutter/packages/flutter/lib/fix_data/fix_template.yaml+1-1
- flutter/packages/flutter/lib/src/animation/animation.dart+120-23
- flutter/packages/flutter/lib/src/animation/animation_controller.dart+243-129
- flutter/packages/flutter/lib/src/animation/animation_style.dart+17-19
- flutter/packages/flutter/lib/src/animation/animations.dart+46-57
- flutter/packages/flutter/lib/src/animation/curves.dart+176-73
- flutter/packages/flutter/lib/src/animation/listener_helpers.dart+40-34
- flutter/packages/flutter/lib/src/animation/tween.dart+26-20
- flutter/packages/flutter/lib/src/animation/tween_sequence.dart+2-6
- flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart+21-32
- flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart+13-10
- flutter/packages/flutter/lib/src/cupertino/app.dart+167-36
- flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart+33-38
- flutter/packages/flutter/lib/src/cupertino/button.dart+367-74
- flutter/packages/flutter/lib/src/cupertino/checkbox.dart+311-73
- flutter/packages/flutter/lib/src/cupertino/colors.dart+187-110
- flutter/packages/flutter/lib/src/cupertino/constants.dart+77
- flutter/packages/flutter/lib/src/cupertino/context_menu.dart+314-399
- flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart+24-37
- flutter/packages/flutter/lib/src/cupertino/date_picker.dart+785-449
- flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart+20-18
- flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart+17-37
- flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart+18-24
- flutter/packages/flutter/lib/src/cupertino/dialog.dart
- flutter/packages/flutter/lib/src/cupertino/form_row.dart+8-18
- flutter/packages/flutter/lib/src/cupertino/form_section.dart+60-42
- flutter/packages/flutter/lib/src/cupertino/icons.dart
- flutter/packages/flutter/lib/src/cupertino/interface_level.dart+5-6
- flutter/packages/flutter/lib/src/cupertino/list_section.dart+100-67
- flutter/packages/flutter/lib/src/cupertino/list_tile.dart+81-85
- flutter/packages/flutter/lib/src/cupertino/localizations.dart+32-9
- flutter/packages/flutter/lib/src/cupertino/magnifier.dart+115-65
- flutter/packages/flutter/lib/src/cupertino/nav_bar.dart
- flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart+94-58
- flutter/packages/flutter/lib/src/cupertino/picker.dart+83-24
- flutter/packages/flutter/lib/src/cupertino/radio.dart+265-58
- flutter/packages/flutter/lib/src/cupertino/refresh.dart+60-37
- flutter/packages/flutter/lib/src/cupertino/route.dart+511-318
- flutter/packages/flutter/lib/src/cupertino/scrollbar.dart+31-23
- flutter/packages/flutter/lib/src/cupertino/search_field.dart+127-44
- flutter/packages/flutter/lib/src/cupertino/segmented_control.dart+115-60
- flutter/packages/flutter/lib/src/cupertino/sheet.dartAdded+825
- flutter/packages/flutter/lib/src/cupertino/slider.dart+48-39
- flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart+370-120
25 unmodified lines262728293031323325 unmodified linesFor more documentation about Data Driven Fixes, seehttps://dart.dev/go/data-driven-fixes#test-folder.To learn more about how fixes are authored in package:flutter, seehttps://github.com/flutter/flutter/wiki/Data-driven-Fixes## When making structural changes to this directory25 unmodified lines2627282930313225 unmodified linesFor more documentation about Data Driven Fixes, seehttps://dart.dev/go/data-driven-fixes#test-folder.To learn more about how fixes are authored in package:flutter, see [Data driven Fixes](../../../../docs/contributing/Data-driven-Fixes.md).## When making structural changes to this directory
2 unmodified lines3456789285 unmodified lines2952962972982 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change285 unmodified lines- kind: 'rename'newName: 'buildOverscrollIndicator'# Before adding a new fix: read instructions at the top of this file.2 unmodified lines3456789285 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304312 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change285 unmodified lines- kind: 'rename'newName: 'buildOverscrollIndicator'# Changes made in https://github.com/flutter/flutter/pull/151367- title: "Rename to 'activeTrackColor'"date: 2024-07-15element:uris: [ 'cupertino.dart' ]getter: 'activeColor'inClass: 'CupertinoSwitch'changes:- kind: 'rename'newName: 'activeTrackColor'# Changes made in https://github.com/flutter/flutter/pull/151367- title: "Migrate to 'activeTrackColor'"date: 2024-07-15element:uris: [ 'cupertino.dart' ]constructor: ''inClass: 'CupertinoSwitch'changes:- kind: 'renameParameter'oldName: 'activeColor'newName: 'activeTrackColor'# Changes made in https://github.com/flutter/flutter/pull/151367- title: "Rename to 'inactiveTrackColor'"date: 2024-07-15element:uris: [ 'cupertino.dart' ]getter: 'trackColor'inClass: 'CupertinoSwitch'changes:- kind: 'rename'newName: 'inactiveTrackColor'# Changes made in https://github.com/flutter/flutter/pull/151367- title: "Migrate to 'inactiveTrackColor'"date: 2024-07-15element:uris: [ 'cupertino.dart' ]constructor: ''inClass: 'CupertinoSwitch'changes:- kind: 'renameParameter'oldName: 'trackColor'newName: 'inactiveTrackColor'# Changes made in https://github.com/flutter/flutter/pull/152981- title: "Replace with 'fillColor'"date: 2024-08-08element:uris: [ 'cupertino.dart' ]constructor: ''inClass: 'CupertinoCheckbox'oneOf:- if: "fillColor == '' && activeColor != ''"changes:- kind: 'addParameter'index: 5name: 'fillColor'style: optional_namedargumentValue:expression: "WidgetStateProperty.resolveWith<Color>((Set<WidgetState> states) {\nif (states.contains(WidgetState.disabled)) {\nreturn CupertinoColors.white.withOpacity(0.5);\n}\nif (states.contains(WidgetState.selected)) {\nreturn {% activeColor %};\n}\nreturn {% inactiveColor %};\n})"requiredIf: "inactiveColor != ''"- kind: 'removeParameter'name: inactiveColor- if: "fillColor == '' && activeColor == ''"changes:- kind: 'addParameter'index: 5name: 'fillColor'style: optional_namedargumentValue:expression: "WidgetStateProperty.resolveWith<Color>((Set<WidgetState> states) {\nif (states.contains(WidgetState.disabled)) {\nreturn CupertinoColors.white.withOpacity(0.5);\n}\nif (states.contains(WidgetState.selected)) {\nreturn CupertinoDynamicColor.resolve(CupertinoDynamicColor.withBrightness(\ncolor: CupertinoColors.activeBlue,\ndarkColor: Color.fromARGB(255, 50, 100, 215),\n), context);\n}\nreturn {% inactiveColor %};\n})"requiredIf: "inactiveColor != ''"- kind: 'removeParameter'name: inactiveColor- if: "fillColor != ''"changes:- kind: 'removeParameter'name: inactiveColorvariables:inactiveColor:kind: fragmentvalue: 'arguments[inactiveColor]'activeColor:kind: fragmentvalue: 'arguments[activeColor]'fillColor:kind: fragmentvalue: 'arguments[fillColor]'# Changes made in https://github.com/flutter/flutter/pull/161295- title: "Migrate 'minSize' to 'minimumSize'"date: 2025-01-09element:uris: [ 'cupertino.dart' ]constructor: ''inClass: 'CupertinoButton'oneOf:- if: "minSize != ''"changes:- kind: 'addParameter'index: 7name: 'minimumSize'style: optional_namedargumentValue:expression: 'Size({% minSize %}, {% minSize %})'requiredIf: "minSize != ''"- kind: 'removeParameter'name: 'minSize'variables:minSize:kind: fragmentvalue: 'arguments[minSize]'# Before adding a new fix: read instructions at the top of this file.
2 unmodified lines34567892 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change2 unmodified lines34567892 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change
2 unmodified lines3456789107 unmodified lines1171181191202 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change107 unmodified lines- kind: 'rename'newName: 'fromViewPadding'# Before adding a new fix: read instructions at the top of this file.2 unmodified lines3456789107 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641652 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change107 unmodified lines- kind: 'rename'newName: 'fromViewPadding'- title: "Rename from 'opacity' to 'a'"date: 2024-09-10element:uris: [ 'painting.dart' ]method: 'opacity'inClass: 'Color'changes:- kind: 'rename'newName: 'a'- title: "Replace 'value' with 'toARGB32()'"date: 2025-02-03element:uris: [ 'painting.dart' ]method: 'value'inClass: 'Color'changes:- kind: 'replacedBy'newElement:uris: [ 'painting.dart' ]method: 'toARGB32'inClass: 'Color'- title: "Rename 'withOpacity'"date: 2024-09-10element:uris: [ 'painting.dart' ]method: 'withOpacity'inClass: 'Color'changes:- kind: 'rename'newName: 'withValues'- kind: 'removeParameter'index: 0- kind: 'addParameter'index: 0name: 'alpha'style: optional_namedargumentValue:expression: '{% opacity %}'requiredIf: "opacity != ''"variables:opacity:kind: 'fragment'value: 'arguments[0]'# Before adding a new fix: read instructions at the top of this file.
2 unmodified lines345678998 unmodified lines1081091101111121131144 unmodified lines1191201211221231241252 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change98 unmodified lineskind: 'fragment'value: 'arguments[overflow]'# Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior- title: "Migrate to 'clipBehavior'"date: 2020-08-20element:4 unmodified lines- kind: 'rename'newName: 'clipBehavior'# Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior- title: "Migrate to 'clipBehavior'"date: 2020-08-20element:2 unmodified lines345678998 unmodified lines1081091101111121131144 unmodified lines1191201211221231241252 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change98 unmodified lineskind: 'fragment'value: 'arguments[overflow]'# Changes made in https://docs.flutter.dev/release/breaking-changes/clip-behavior- title: "Migrate to 'clipBehavior'"date: 2020-08-20element:4 unmodified lines- kind: 'rename'newName: 'clipBehavior'# Changes made in https://docs.flutter.dev/release/breaking-changes/clip-behavior- title: "Migrate to 'clipBehavior'"date: 2020-08-20element:
2 unmodified lines345678974 unmodified lines848586872 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change74 unmodified lineskind: 'fragment'value: 'arguments[0]'# Before adding a new fix: read instructions at the top of this file.2 unmodified lines345678974 unmodified lines848586878889909192939495969798991001012 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change74 unmodified lineskind: 'fragment'value: 'arguments[0]'# Changes made in https://github.com/flutter/flutter/pull/161518- title: "Migrate 'SelectionChangedCause.scribble' to 'SelectionChangedCause.stylusHandwriting'"date: 2025-01-13element:uris: [ 'services.dart' ]constant: 'scribble'inEnum: 'SelectionChangedCause'changes:- kind: 'replacedBy'newElement:uris: [ 'services.dart' ]constant: 'stylusHandwriting'inEnum: 'SelectionChangedCause'# Before adding a new fix: read instructions at the top of this file.
2 unmodified lines34567892 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/docs/development/tools/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change2 unmodified lines34567892 unmodified lines# found in the LICENSE file.# For details regarding the *Flutter Fix* feature, see# https://flutter.dev/to/flutter-fix# Please add new fixes to the top of the file, separated by one blank line# from other fixes. In a comment, include a link to the PR where the change
1 unmodified line23456719 unmodified lines272829303132332 unmodified lines363738394041424344454647484950515253545556575859601 unmodified line6263646566676839 unmodified lines10810911011111211311435 unmodified lines15015115215315415515615715815923 unmodified lines18318418518618718818980 unmodified lines2702712722732742752762772 unmodified lines2802812822832842852862872881 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';19 unmodified linesreverse,/// The animation is stopped at the end.completed,}/// Signature for listeners attached using [Animation.addStatusListener].2 unmodified lines/// Signature for method used to transform values in [Animation.fromValueListenable].typedef ValueListenableTransformer<T> = T Function(T);/// An animation with a value of type `T`.////// An animation consists of a value (of type `T`) together with a status. The/// status indicates whether the animation is conceptually running from/// beginning to end or from the end back to the beginning, although the actual/// value of the animation might not change monotonically (e.g., if the/// animation uses a curve that bounces).////// Animations also let other objects listen for changes to either their value/// or their status. These callbacks are called during the "animation" phase of/// the pipeline, just prior to rebuilding widgets.////// To create a new animation that you can run forward and backward, consider/// using [AnimationController].////// See also:////// * [Tween], which can be used to create [Animation] subclasses that/// convert `Animation<double>`s into other kinds of [Animation]s.abstract class Animation<T> extends Listenable implements ValueListenable<T> {/// Abstract const constructor. This constructor enables subclasses to provide/// const constructors so that they can be used in const expressions.1 unmodified line/// Create a new animation from a [ValueListenable].////// The returned animation will always have an animations status of/// [AnimationStatus.forward]. The value of the provided listenable can/// be optionally transformed using the [transformer] function.///39 unmodified lines/// }/// ```/// {@end-tool}factory Animation.fromValueListenable(ValueListenable<T> listenable, {ValueListenableTransformer<T>? transformer,}) = _ValueListenableDelegateAnimation<T>;35 unmodified linesT get value;/// Whether this animation is stopped at the beginning.bool get isDismissed => status == AnimationStatus.dismissed;/// Whether this animation is stopped at the end.bool get isCompleted => status == AnimationStatus.completed;/// Chains a [Tween] (or [CurveTween]) to this [Animation].///23 unmodified lines/// {@end-tool}/// {@tool snippet}////// The `_alignment.value` could then be used in a widget's build method, for/// instance, to position a child using an [Align] widget such that the/// position of the child shifts over time from the top left to the top right.///80 unmodified lines/// * "⏮": [AnimationStatus.dismissed] ([value] == 0.0)String toStringDetails() {return switch (status) {AnimationStatus.forward => '\u25B6', // >AnimationStatus.reverse => '\u25C0', // <AnimationStatus.completed => '\u23ED', // >>|AnimationStatus.dismissed => '\u23EE', // |<<};2 unmodified lines// An implementation of an animation that delegates to a value listenable with a fixed direction.class _ValueListenableDelegateAnimation<T> extends Animation<T> {_ValueListenableDelegateAnimation(this._listenable, {ValueListenableTransformer<T>? transformer,}) : _transformer = transformer;final ValueListenable<T> _listenable;final ValueListenableTransformer<T>? _transformer;1 unmodified line234567891019 unmodified lines303132333435363738394041424344454647484950515253545556575859602 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471 unmodified line14915015115215315415539 unmodified lines19519619719819920020120235 unmodified lines23823924024124224324424524624724824925025125225325425525625723 unmodified lines28128228328428528628780 unmodified lines3683693703713723733743752 unmodified lines3783793803813823833843851 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/scheduler.dart';/// @docImport 'package:flutter/widgets.dart';library;import 'package:flutter/foundation.dart';19 unmodified linesreverse,/// The animation is stopped at the end.completed;/// Whether the animation is stopped at the beginning.bool get isDismissed => this == dismissed;/// Whether the animation is stopped at the end.bool get isCompleted => this == completed;/// Whether the animation is running in either direction.bool get isAnimating => switch (this) {forward || reverse => true,completed || dismissed => false,};/// {@template flutter.animation.AnimationStatus.isForwardOrCompleted}/// Whether the current aim of the animation is toward completion.////// Specifically, returns `true` for [AnimationStatus.forward] or/// [AnimationStatus.completed], and `false` for/// [AnimationStatus.reverse] or [AnimationStatus.dismissed]./// {@endtemplate}bool get isForwardOrCompleted => switch (this) {forward || completed => true,reverse || dismissed => false,};}/// Signature for listeners attached using [Animation.addStatusListener].2 unmodified lines/// Signature for method used to transform values in [Animation.fromValueListenable].typedef ValueListenableTransformer<T> = T Function(T);/// A value which might change over time, moving forward or backward.////// An animation has a [value] (of type [T]) and a [status]./// The value conceptually lies on some path, and/// the status indicates how the value is currently moving along the path:/// forward, backward, or stopped at the end or the beginning./// The path may double back on itself/// (e.g., if the animation uses a curve that bounces),/// so even when the animation is conceptually moving forward/// the value might not change monotonically.////// Consumers of the animation can listen for changes to either the value/// or the status, with [addListener] and [addStatusListener]./// The listener callbacks are called during the "animation" phase of/// the pipeline, just prior to rebuilding widgets.////// An animation might move forward or backward on its own as time passes/// (like the opacity of a button that fades over a fixed duration/// once the user touches it),/// or it might be driven by the user/// (like the position of a slider that the user can drag back and forth),/// or it might do both/// (like a switch that snaps into place when released,/// or a [Dismissible] that responds to drag and fling gestures, etc.)./// The behavior is normally controlled by method calls on/// some underlying [AnimationController]./// When an animation is actively animating, it typically updates on/// each frame, driven by a [Ticker].////// ## Using animations////// For simple animation effects, consider using one of the/// [ImplicitlyAnimatedWidget] subclasses,/// like [AnimatedScale], [AnimatedOpacity], and many others./// When an [ImplicitlyAnimatedWidget] suffices, there is/// no need to work with [Animation] or the rest of the classes/// discussed in this section.////// Otherwise, typically an animation originates with an [AnimationController]/// (which is itself an [Animation<double>])/// created by a [State] that implements [TickerProvider]./// Further animations might be derived from that animation/// by using e.g. [Tween] or [CurvedAnimation]./// The animations might be used to configure an [AnimatedWidget]/// (using one of its many subclasses like [FadeTransition]),/// or their values might be used directly.////// For example, the [AnimationController] may represent/// the abstract progress of the animation from 0.0 to 1.0;/// then a [CurvedAnimation] might apply an easing curve;/// and a [SizeTween] and [ColorTween] might each be applied to that/// to produce an [Animation<Size>] and an [Animation<Color>] that control/// a widget shrinking and changing color as the animation proceeds.////// ## Performance considerations////// Because the [Animation] keeps the same identity as the animation proceeds,/// it provides a convenient way for a [StatefulWidget] that orchestrates/// a complex animation to communicate the animation's progress to its/// various child widgets. Consider having higher-level widgets in the tree/// pass lower-level widgets the [Animation] itself, rather than its value,/// in order to avoid rebuilding the higher-level widgets on each frame/// even while the animation is active./// If the leaf widgets also ignore [value] and pass the whole/// [Animation] object to a render object (like [FadeTransition] does),/// they too might be able to avoid rebuild and even relayout, so that the/// only work needed on each frame of the animation is to repaint.////// See also:////// * [ImplicitlyAnimatedWidget] and its subclasses, which provide/// animation effects without the need to manually work with [Animation],/// [AnimationController], or even [State]./// * [AnimationController], an animation you can run forward and backward,/// stop, or set to a specific value./// * [Tween], which can be used to convert [Animation<double>]s into/// other kinds of [Animation]s./// * [AnimatedWidget] and its subclasses, which provide animation effects/// that can be controlled by an [Animation].abstract class Animation<T> extends Listenable implements ValueListenable<T> {/// Abstract const constructor. This constructor enables subclasses to provide/// const constructors so that they can be used in const expressions.1 unmodified line/// Create a new animation from a [ValueListenable].////// The returned animation will always have an animation status of/// [AnimationStatus.forward]. The value of the provided listenable can/// be optionally transformed using the [transformer] function.///39 unmodified lines/// }/// ```/// {@end-tool}factory Animation.fromValueListenable(ValueListenable<T> listenable, {ValueListenableTransformer<T>? transformer,}) = _ValueListenableDelegateAnimation<T>;35 unmodified linesT get value;/// Whether this animation is stopped at the beginning.bool get isDismissed => status.isDismissed;/// Whether this animation is stopped at the end.bool get isCompleted => status.isCompleted;/// Whether this animation is running in either direction.////// By default, this value is equal to `status.isAnimating`, but/// [AnimationController] overrides this method so that its output/// depends on whether the controller is actively ticking.bool get isAnimating => status.isAnimating;/// {@macro flutter.animation.AnimationStatus.isForwardOrCompleted}bool get isForwardOrCompleted => status.isForwardOrCompleted;/// Chains a [Tween] (or [CurveTween]) to this [Animation].///23 unmodified lines/// {@end-tool}/// {@tool snippet}////// The `alignment1.value` could then be used in a widget's build method, for/// instance, to position a child using an [Align] widget such that the/// position of the child shifts over time from the top left to the top right.///80 unmodified lines/// * "⏮": [AnimationStatus.dismissed] ([value] == 0.0)String toStringDetails() {return switch (status) {AnimationStatus.forward => '\u25B6', // >AnimationStatus.reverse => '\u25C0', // <AnimationStatus.completed => '\u23ED', // >>|AnimationStatus.dismissed => '\u23EE', // |<<};2 unmodified lines// An implementation of an animation that delegates to a value listenable with a fixed direction.class _ValueListenableDelegateAnimation<T> extends Animation<T> {_ValueListenableDelegateAnimation(this._listenable, {ValueListenableTransformer<T>? transformer}): _transformer = transformer;final ValueListenable<T> _listenable;final ValueListenableTransformer<T>? _transformer;
1 unmodified line23456712 unmodified lines202122232425262713 unmodified lines4142434445464748495030 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114105 unmodified lines2202212222232242252262272282292302312325 unmodified lines2382392402412422432442452462472482499 unmodified lines25926026126226326426526626725 unmodified lines29329429529629729829930030130230330430530630730830931031131231331431531651 unmodified lines36836937037137237313 unmodified lines38738838939039139239339427 unmodified lines4224234244254264274283 unmodified lines43243343443543643743843944010 unmodified lines4514524534544554566 unmodified lines4634644654664674681 unmodified line47047147247347447547620 unmodified lines4974984995005015021 unmodified line50450550650750850951016 unmodified lines5275285295305315325339 unmodified lines54354454554654754854914 unmodified lines5645655665675685695705 unmodified lines57657757857958058158214 unmodified lines5975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266275 unmodified lines63363463563663763863964064164264364464564664711 unmodified lines65966066166266366466566666766866967067110 unmodified lines68268368468568668768868969069169269369469569619 unmodified lines7167177187197207217227237247257267277287297307317327337347357367377387 unmodified lines7467477487497507513 unmodified lines7557567577587597607617627635 unmodified lines76977077177277377477577677777877978078178278315 unmodified lines79980080180280380480526 unmodified lines83283383483583683783883984012 unmodified lines85385485585685785885986086186286386486529 unmodified lines8958968978988999009019029039049059069079 unmodified lines9179189199209219229239249251 unmodified line92792892993093193293393493593693715 unmodified lines9539549559569571 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:ui' as ui show lerpDouble;12 unmodified linesexport 'animation.dart' show Animation, AnimationStatus;export 'curves.dart' show Curve;const String _flutterAnimationLibrary = 'package:flutter/animation.dart';// Examples can assume:// late AnimationController _controller, fadeAnimationController, sizeAnimationController;// late bool dismissed;13 unmodified linesstiffness: 500.0,);const Tolerance _kFlingTolerance = Tolerance(velocity: double.infinity,distance: 0.01,);/// Configures how an [AnimationController] behaves when animations are/// disabled.30 unmodified lines/// * Create a [fling] animation effect using a physics simulation.////// By default, an [AnimationController] linearly produces values that range/// from 0.0 to 1.0, during a given duration. The animation controller generates/// a new value whenever the device running your app is ready to display a new/// frame (typically, this rate is around 60 values per second).////// ## Ticker providers////// An [AnimationController] needs a [TickerProvider], which is configured using/// the `vsync` argument on the constructor.////// The [TickerProvider] interface describes a factory for [Ticker] objects. A/// [Ticker] is an object that knows how to register itself with the/// [SchedulerBinding] and fires a callback every frame. The/// [AnimationController] class uses a [Ticker] to step through the animation/// that it controls.////// If an [AnimationController] is being created from a [State], then the State/// can use the [TickerProviderStateMixin] and [SingleTickerProviderStateMixin]/// classes to implement the [TickerProvider] interface. The/// [TickerProviderStateMixin] class always works for this purpose; the/// [SingleTickerProviderStateMixin] is slightly more efficient in the case of/// the class only ever needing one [Ticker] (e.g. if the class creates only a/// single [AnimationController] during its entire lifetime).////// The widget test framework [WidgetTester] object can be used as a ticker/// provider in the context of tests. In other contexts, you will have to either/// pass a [TickerProvider] from a higher level (e.g. indirectly from a [State]/// that mixes in [TickerProviderStateMixin]), or create a custom/// [TickerProvider] subclass.////// ## Life cycle///105 unmodified lines////// ** See code in examples/api/lib/animation/animation_controller/animated_digit.0.dart **/// {@end-tool}/// See also:////// * [Tween], the base class for converting an [AnimationController] to a/// range of values of other types.class AnimationController extends Animation<double>with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {/// Creates an animation controller.////// * `value` is the initial value of the animation. If defaults to the lower5 unmodified lines/// debugging (used by [toString]).////// * [lowerBound] is the smallest value this animation can obtain and the/// value at which this animation is deemed to be dismissed. It cannot be/// null.////// * [upperBound] is the largest value this animation can obtain and the/// value at which this animation is deemed to be completed. It cannot be/// null.////// * `vsync` is the required [TickerProvider] for the current context. It can/// be changed by calling [resync]. See [TickerProvider] for advice on9 unmodified linesrequired TickerProvider vsync,}) : assert(upperBound >= lowerBound),_direction = _AnimationDirection.forward {if (kFlutterMemoryAllocationsEnabled) {_maybeDispatchObjectCreation();}_ticker = vsync.createTicker(_tick);_internalSetValue(value ?? lowerBound);}25 unmodified lines}) : lowerBound = double.negativeInfinity,upperBound = double.infinity,_direction = _AnimationDirection.forward {if (kFlutterMemoryAllocationsEnabled) {_maybeDispatchObjectCreation();}_ticker = vsync.createTicker(_tick);_internalSetValue(value);}/// Dispatches event of object creation to [FlutterMemoryAllocations.instance].void _maybeDispatchObjectCreation() {if (kFlutterMemoryAllocationsEnabled) {FlutterMemoryAllocations.instance.dispatchObjectCreated(library: _flutterAnimationLibrary,className: '$AnimationController',object: this,);}}/// The value at which this animation is deemed to be dismissed.final double lowerBound;51 unmodified lines@overridedouble get value => _value;late double _value;/// Stops the animation controller and sets the current value of the/// animation.///13 unmodified lines/// * [stop], which aborts the animation without changing its value or status/// and without dispatching any notifications other than completing or/// canceling the [TickerFuture]./// * [forward], [reverse], [animateTo], [animateWith], [fling], and [repeat],/// which start the animation controller.set value(double newValue) {stop();_internalSetValue(newValue);27 unmodified linesif (!isAnimating) {return 0.0;}return _simulation!.dx(lastElapsedDuration!.inMicroseconds.toDouble() / Duration.microsecondsPerSecond);}void _internalSetValue(double newValue) {3 unmodified lines} else if (_value == upperBound) {_status = AnimationStatus.completed;} else {_status = (_direction == _AnimationDirection.forward) ?AnimationStatus.forward :AnimationStatus.reverse;}}10 unmodified lines/// controller's ticker might get muted, in which case the animation/// controller's callbacks will no longer fire even though time is continuing/// to pass. See [Ticker.muted] and [TickerMode].bool get isAnimating => _ticker != null && _ticker!.isActive;_AnimationDirection _direction;6 unmodified lines////// Returns a [TickerFuture] that completes when the animation is complete.////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.1 unmodified line/// During the animation, [status] is reported as [AnimationStatus.forward],/// which switches to [AnimationStatus.completed] when [upperBound] is/// reached at the end of the animation.TickerFuture forward({ double? from }) {assert(() {if (duration == null) {throw FlutterError(20 unmodified lines////// Returns a [TickerFuture] that completes when the animation is dismissed.////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.1 unmodified line/// During the animation, [status] is reported as [AnimationStatus.reverse],/// which switches to [AnimationStatus.dismissed] when [lowerBound] is/// reached at the end of the animation.TickerFuture reverse({ double? from }) {assert(() {if (duration == null && reverseDuration == null) {throw FlutterError(16 unmodified linesreturn _animateToInternal(lowerBound);}/// Drives the animation from its current value to target.////// Returns a [TickerFuture] that completes when the animation is complete.///9 unmodified lines/// If the `target` argument is the same as the current [value] of the/// animation, then this won't animate, and the returned [TickerFuture] will/// be already complete.TickerFuture animateTo(double target, { Duration? duration, Curve curve = Curves.linear }) {assert(() {if (this.duration == null && duration == null) {throw FlutterError(14 unmodified linesreturn _animateToInternal(target, duration: duration, curve: curve);}/// Drives the animation from its current value to target.////// Returns a [TickerFuture] that completes when the animation is complete.///5 unmodified lines/// regardless of whether `target` < [value] or not. At the end of the/// animation, when `target` is reached, [status] is reported as/// [AnimationStatus.dismissed].TickerFuture animateBack(double target, { Duration? duration, Curve curve = Curves.linear }) {assert(() {if (this.duration == null && reverseDuration == null && duration == null) {throw FlutterError(14 unmodified linesreturn _animateToInternal(target, duration: duration, curve: curve);}TickerFuture _animateToInternal(double target, { Duration? duration, Curve curve = Curves.linear }) {double scale = 1.0;if (SemanticsBinding.instance.disableAnimations) {switch (animationBehavior) {case AnimationBehavior.normal:// Since the framework cannot handle zero duration animations, we run it at 5% of the normal// duration to limit most animations to a single frame.// Ideally, the framework would be able to handle zero duration animations, however, the common// pattern of an eternally repeating animation might cause an endless loop if it weren't delayed// for at least one frame.scale = 0.05;case AnimationBehavior.preserve:break;}}Duration? simulationDuration = duration;if (simulationDuration == null) {assert(!(this.duration == null && _direction == _AnimationDirection.forward));assert(!(this.duration == null && _direction == _AnimationDirection.reverse && reverseDuration == null));final double range = upperBound - lowerBound;final double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0;final Duration directionDuration =(_direction == _AnimationDirection.reverse && reverseDuration != null)? reverseDuration!: this.duration!;simulationDuration = directionDuration * remainingFraction;} else if (target == value) {// Already at target, don't animate.5 unmodified lines_value = clampDouble(target, lowerBound, upperBound);notifyListeners();}_status = (_direction == _AnimationDirection.forward) ?AnimationStatus.completed :AnimationStatus.dismissed;_checkStatusChanged();return TickerFuture.complete();}assert(simulationDuration > Duration.zero);assert(!isAnimating);return _startSimulation(_InterpolationSimulation(_value, target, simulationDuration, curve, scale));}/// Starts running this animation in the forward direction, and11 unmodified lines/// provided, [duration] will be used instead, which has to be set before [repeat] is/// called either in the constructor or later by using the [duration] setter.////// Returns a [TickerFuture] that never completes. The [TickerFuture.orCancel] future/// completes with an error when the animation is stopped (e.g. with [stop]).////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.TickerFuture repeat({ double? min, double? max, bool reverse = false, Duration? period }) {min ??= lowerBound;max ??= upperBound;period ??= duration;10 unmodified lines}());assert(max >= min);assert(max <= upperBound && min >= lowerBound);stop();return _startSimulation(_RepeatingSimulation(_value, min, max, reverse, period!, _directionSetter));}void _directionSetter(_AnimationDirection direction) {_direction = direction;_status = (_direction == _AnimationDirection.forward) ?AnimationStatus.forward :AnimationStatus.reverse;_checkStatusChanged();}19 unmodified lines/// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.TickerFuture fling({ double velocity = 1.0, SpringDescription? springDescription, AnimationBehavior? animationBehavior }) {springDescription ??= _kFlingSpringDescription;_direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward;final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance: upperBound + _kFlingTolerance.distance;double scale = 1.0;final AnimationBehavior behavior = animationBehavior ?? this.animationBehavior;if (SemanticsBinding.instance.disableAnimations) {switch (behavior) {case AnimationBehavior.normal:scale = 200.0; // This is arbitrary (it was chosen because it worked for the drawer widget).case AnimationBehavior.preserve:break;}}final SpringSimulation simulation = SpringSimulation(springDescription, value, target, velocity * scale)..tolerance = _kFlingTolerance;assert(simulation.type != SpringType.underDamped,'The specified spring simulation is of type SpringType.underDamped.\n'7 unmodified lines/// Drives the animation according to the given simulation.////// The values from the simulation are clamped to the [lowerBound] and/// [upperBound]. To avoid this, consider creating the [AnimationController]/// using the [AnimationController.unbounded] constructor.3 unmodified lines/// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.////// The [status] is always [AnimationStatus.forward] for the entire duration/// of the simulation.TickerFuture animateWith(Simulation simulation) {assert(_ticker != null,5 unmodified linesreturn _startSimulation(simulation);}TickerFuture _startSimulation(Simulation simulation) {assert(!isAnimating);_simulation = simulation;_lastElapsedDuration = Duration.zero;_value = clampDouble(simulation.x(0.0), lowerBound, upperBound);final TickerFuture result = _ticker!.start();_status = (_direction == _AnimationDirection.forward) ?AnimationStatus.forward :AnimationStatus.reverse;_checkStatusChanged();return result;}15 unmodified lines/// and which does send notifications./// * [forward], [reverse], [animateTo], [animateWith], [fling], and [repeat],/// which restart the animation controller.void stop({ bool canceled = true }) {assert(_ticker != null,'AnimationController.stop() called after AnimationController.dispose()\n'26 unmodified lines}return true;}());if (kFlutterMemoryAllocationsEnabled) {FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);}_ticker!.dispose();_ticker = null;clearStatusListeners();12 unmodified linesvoid _tick(Duration elapsed) {_lastElapsedDuration = elapsed;final double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.microsecondsPerSecond;assert(elapsedInSeconds >= 0.0);_value = clampDouble(_simulation!.x(elapsedInSeconds), lowerBound, upperBound);if (_simulation!.isDone(elapsedInSeconds)) {_status = (_direction == _AnimationDirection.forward) ?AnimationStatus.completed :AnimationStatus.dismissed;stop(canceled: false);}notifyListeners();29 unmodified lines@overridedouble x(double timeInSeconds) {final double t = clampDouble(timeInSeconds / _durationInSeconds, 0.0, 1.0);if (t == 0.0) {return _begin;} else if (t == 1.0) {return _end;} else {return _begin + (_end - _begin) * _curve.transform(t);}}@override9 unmodified linestypedef _DirectionSetter = void Function(_AnimationDirection direction);class _RepeatingSimulation extends Simulation {_RepeatingSimulation(double initialValue, this.min, this.max, this.reverse, Duration period, this.directionSetter): _periodInSeconds = period.inMicroseconds / Duration.microsecondsPerSecond,_initialT = (max == min) ? 0.0 : (initialValue / (max - min)) * (period.inMicroseconds / Duration.microsecondsPerSecond) {assert(_periodInSeconds > 0.0);assert(_initialT >= 0.0);}1 unmodified linefinal double min;final double max;final bool reverse;final _DirectionSetter directionSetter;final double _periodInSeconds;final double _initialT;@overridedouble x(double timeInSeconds) {assert(timeInSeconds >= 0.0);15 unmodified linesdouble dx(double timeInSeconds) => (max - min) / _periodInSeconds;@overridebool isDone(double timeInSeconds) => false;}1 unmodified line234567891012 unmodified lines23242526272813 unmodified lines4243444546474830 unmodified lines798081828384858687888990919293949596979899100101102103104105106107105 unmodified lines2132142152162172182192202212222232242252262272285 unmodified lines2342352362372382392402412422439 unmodified lines25325425525625725825925 unmodified lines28528628728828929029129229329429551 unmodified lines34734834935035135235313 unmodified lines36736836937037137237337427 unmodified lines4024034044054064074084094103 unmodified lines41441541641741841942042142242310 unmodified lines4344354364374384394404414424434446 unmodified lines4514524534544554564574584591 unmodified line46146246346446546646720 unmodified lines4884894904914924934944954961 unmodified line49849950050150250350416 unmodified lines5215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685699 unmodified lines57958058158258358458514 unmodified lines6006016026036046056065 unmodified lines61261361461561661761861962062162214 unmodified lines6376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696705 unmodified lines67667767867968068168268368468568668768868969069169269311 unmodified lines70570670770870971071171271371471571671771871972072172272372472572672710 unmodified lines73873974074174274374474574674774874975075175275375475575619 unmodified lines7767777787797807817827837847857867877887897907917927937947957967977987998008018028038047 unmodified lines8128138148158168178183 unmodified lines8228238248258268278288298308318328338348358365 unmodified lines84284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988015 unmodified lines89689789889990090190226 unmodified lines92993093193293393493512 unmodified lines94894995095195295395495595695795895996096196229 unmodified lines9929939949959969979989991000100110029 unmodified lines1012101310141015101610171018101910201021102210231024102510261027102810291030103110321 unmodified line1034103510361037103810391040104110421043104410451046104715 unmodified lines1063106410651066106710681069107010711 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/widgets.dart';/// @docImport 'package:flutter_test/flutter_test.dart';library;import 'dart:ui' as ui show lerpDouble;12 unmodified linesexport 'animation.dart' show Animation, AnimationStatus;export 'curves.dart' show Curve;// Examples can assume:// late AnimationController _controller, fadeAnimationController, sizeAnimationController;// late bool dismissed;13 unmodified linesstiffness: 500.0,);const Tolerance _kFlingTolerance = Tolerance(velocity: double.infinity, distance: 0.01);/// Configures how an [AnimationController] behaves when animations are/// disabled.30 unmodified lines/// * Create a [fling] animation effect using a physics simulation.////// By default, an [AnimationController] linearly produces values that range/// from 0.0 to 1.0, during a given duration.////// When the animation is actively animating, the animation controller generates/// a new value each time the device running your app is ready to display a new/// frame (typically, this rate is around 60–120 values per second)./// If the animation controller is associated with a [State]/// through a [TickerProvider], then its updates will be silenced when that/// [State]'s subtree is disabled as defined by [TickerMode]; time will still/// elapse, and methods like [forward] and [stop] can still be called and/// will change the value, but the controller will not generate new values/// on its own.////// ## Ticker providers////// An [AnimationController] needs a [TickerProvider], which is configured using/// the `vsync` argument on the constructor./// The constructor uses the [TickerProvider] to create a [Ticker], which/// the [AnimationController] uses to step through the animation it controls.////// For advice on obtaining a ticker provider, see [TickerProvider]./// Typically the relevant [State] serves as the ticker provider,/// after applying a suitable mixin (like [SingleTickerProviderStateMixin])/// to cause the [State] subclass to implement [TickerProvider].////// ## Life cycle///105 unmodified lines////// ** See code in examples/api/lib/animation/animation_controller/animated_digit.0.dart **/// {@end-tool}////// See also:////// * [Tween], the base class for converting an [AnimationController] to a/// range of values of other types.class AnimationController extends Animation<double>withAnimationEagerListenerMixin,AnimationLocalListenersMixin,AnimationLocalStatusListenersMixin {/// Creates an animation controller.////// * `value` is the initial value of the animation. If defaults to the lower5 unmodified lines/// debugging (used by [toString]).////// * [lowerBound] is the smallest value this animation can obtain and the/// value at which this animation is deemed to be dismissed.////// * [upperBound] is the largest value this animation can obtain and the/// value at which this animation is deemed to be completed.////// * `vsync` is the required [TickerProvider] for the current context. It can/// be changed by calling [resync]. See [TickerProvider] for advice on9 unmodified linesrequired TickerProvider vsync,}) : assert(upperBound >= lowerBound),_direction = _AnimationDirection.forward {assert(debugMaybeDispatchCreated('animation', 'AnimationController', this));_ticker = vsync.createTicker(_tick);_internalSetValue(value ?? lowerBound);}25 unmodified lines}) : lowerBound = double.negativeInfinity,upperBound = double.infinity,_direction = _AnimationDirection.forward {assert(debugMaybeDispatchCreated('animation', 'AnimationController', this));_ticker = vsync.createTicker(_tick);_internalSetValue(value);}/// The value at which this animation is deemed to be dismissed.final double lowerBound;51 unmodified lines@overridedouble get value => _value;late double _value;/// Stops the animation controller and sets the current value of the/// animation.///13 unmodified lines/// * [stop], which aborts the animation without changing its value or status/// and without dispatching any notifications other than completing or/// canceling the [TickerFuture]./// * [forward], [reverse], [animateTo], [animateWith], [animateBackWith],/// [fling], and [repeat], which start the animation controller.set value(double newValue) {stop();_internalSetValue(newValue);27 unmodified linesif (!isAnimating) {return 0.0;}return _simulation!.dx(lastElapsedDuration!.inMicroseconds.toDouble() / Duration.microsecondsPerSecond,);}void _internalSetValue(double newValue) {3 unmodified lines} else if (_value == upperBound) {_status = AnimationStatus.completed;} else {_status = switch (_direction) {_AnimationDirection.forward => AnimationStatus.forward,_AnimationDirection.reverse => AnimationStatus.reverse,};}}10 unmodified lines/// controller's ticker might get muted, in which case the animation/// controller's callbacks will no longer fire even though time is continuing/// to pass. See [Ticker.muted] and [TickerMode].////// If the animation was stopped (e.g. with [stop] or by setting a new [value]),/// [isAnimating] will return `false` but the [status] will not change,/// so the value of [AnimationStatus.isAnimating] might still be `true`.@overridebool get isAnimating => _ticker != null && _ticker!.isActive;_AnimationDirection _direction;6 unmodified lines////// Returns a [TickerFuture] that completes when the animation is complete.////// If [from] is non-null, it will be set as the current [value] before running/// the animation.////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.1 unmodified line/// During the animation, [status] is reported as [AnimationStatus.forward],/// which switches to [AnimationStatus.completed] when [upperBound] is/// reached at the end of the animation.TickerFuture forward({double? from}) {assert(() {if (duration == null) {throw FlutterError(20 unmodified lines////// Returns a [TickerFuture] that completes when the animation is dismissed.////// If [from] is non-null, it will be set as the current [value] before running/// the animation.////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.1 unmodified line/// During the animation, [status] is reported as [AnimationStatus.reverse],/// which switches to [AnimationStatus.dismissed] when [lowerBound] is/// reached at the end of the animation.TickerFuture reverse({double? from}) {assert(() {if (duration == null && reverseDuration == null) {throw FlutterError(16 unmodified linesreturn _animateToInternal(lowerBound);}/// Toggles the direction of this animation, based on whether it [isForwardOrCompleted].////// Specifically, this function acts the same way as [reverse] if the [status] is/// either [AnimationStatus.forward] or [AnimationStatus.completed], and acts as/// [forward] for [AnimationStatus.reverse] or [AnimationStatus.dismissed].////// If [from] is non-null, it will be set as the current [value] before running/// the animation.////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.TickerFuture toggle({double? from}) {assert(() {Duration? duration = this.duration;if (isForwardOrCompleted) {duration ??= reverseDuration;}if (duration == null) {throw FlutterError('AnimationController.toggle() called with no default duration.\n''The "duration" property should be set, either in the constructor or later, before ''calling the toggle() function.',);}return true;}());assert(_ticker != null,'AnimationController.toggle() called after AnimationController.dispose()\n''AnimationController methods should not be used after calling dispose.',);_direction = isForwardOrCompleted ? _AnimationDirection.reverse : _AnimationDirection.forward;if (from != null) {value = from;}return _animateToInternal(switch (_direction) {_AnimationDirection.forward => upperBound,_AnimationDirection.reverse => lowerBound,});}/// Drives the animation from its current value to the given target, "forward".////// Returns a [TickerFuture] that completes when the animation is complete.///9 unmodified lines/// If the `target` argument is the same as the current [value] of the/// animation, then this won't animate, and the returned [TickerFuture] will/// be already complete.TickerFuture animateTo(double target, {Duration? duration, Curve curve = Curves.linear}) {assert(() {if (this.duration == null && duration == null) {throw FlutterError(14 unmodified linesreturn _animateToInternal(target, duration: duration, curve: curve);}/// Drives the animation from its current value to the given target, "backward".////// Returns a [TickerFuture] that completes when the animation is complete.///5 unmodified lines/// regardless of whether `target` < [value] or not. At the end of the/// animation, when `target` is reached, [status] is reported as/// [AnimationStatus.dismissed].////// If the `target` argument is the same as the current [value] of the/// animation, then this won't animate, and the returned [TickerFuture] will/// be already complete.TickerFuture animateBack(double target, {Duration? duration, Curve curve = Curves.linear}) {assert(() {if (this.duration == null && reverseDuration == null && duration == null) {throw FlutterError(14 unmodified linesreturn _animateToInternal(target, duration: duration, curve: curve);}TickerFuture _animateToInternal(double target, {Duration? duration,Curve curve = Curves.linear,}) {final double scale = switch (animationBehavior) {// Since the framework cannot handle zero duration animations, we run it at 5% of the normal// duration to limit most animations to a single frame.// Ideally, the framework would be able to handle zero duration animations, however, the common// pattern of an eternally repeating animation might cause an endless loop if it weren't delayed// for at least one frame.AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 0.05,AnimationBehavior.normal || AnimationBehavior.preserve => 1.0,};Duration? simulationDuration = duration;if (simulationDuration == null) {assert(!(this.duration == null && _direction == _AnimationDirection.forward));assert(!(this.duration == null &&_direction == _AnimationDirection.reverse &&reverseDuration == null),);final double range = upperBound - lowerBound;final double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0;final Duration directionDuration =(_direction == _AnimationDirection.reverse && reverseDuration != null)? reverseDuration!: this.duration!;simulationDuration = directionDuration * remainingFraction;} else if (target == value) {// Already at target, don't animate.5 unmodified lines_value = clampDouble(target, lowerBound, upperBound);notifyListeners();}_status =(_direction == _AnimationDirection.forward)? AnimationStatus.completed: AnimationStatus.dismissed;_checkStatusChanged();return TickerFuture.complete();}assert(simulationDuration > Duration.zero);assert(!isAnimating);return _startSimulation(_InterpolationSimulation(_value, target, simulationDuration, curve, scale),);}/// Starts running this animation in the forward direction, and11 unmodified lines/// provided, [duration] will be used instead, which has to be set before [repeat] is/// called either in the constructor or later by using the [duration] setter.////// If a value is passed to [count], the animation will perform that many/// iterations before stopping. Otherwise, the animation repeats indefinitely.////// Returns a [TickerFuture] that never completes, unless a [count] is specified./// The [TickerFuture.orCancel] future completes with an error when the animation is/// stopped (e.g. with [stop]).////// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.TickerFuture repeat({double? min,double? max,bool reverse = false,Duration? period,int? count,}) {min ??= lowerBound;max ??= upperBound;period ??= duration;10 unmodified lines}());assert(max >= min);assert(max <= upperBound && min >= lowerBound);assert(count == null || count > 0, 'Count shall be greater than zero if not null');stop();return _startSimulation(_RepeatingSimulation(_value, min, max, reverse, period!, _directionSetter, count),);}void _directionSetter(_AnimationDirection direction) {_direction = direction;_status =(_direction == _AnimationDirection.forward)? AnimationStatus.forward: AnimationStatus.reverse;_checkStatusChanged();}19 unmodified lines/// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error.TickerFuture fling({double velocity = 1.0,SpringDescription? springDescription,AnimationBehavior? animationBehavior,}) {springDescription ??= _kFlingSpringDescription;_direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward;final double target =velocity < 0.0? lowerBound - _kFlingTolerance.distance: upperBound + _kFlingTolerance.distance;final AnimationBehavior behavior = animationBehavior ?? this.animationBehavior;final double scale = switch (behavior) {// This is arbitrary (it was chosen because it worked for the drawer widget).AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 200.0,AnimationBehavior.normal || AnimationBehavior.preserve => 1.0,};final SpringSimulation simulation = SpringSimulation(springDescription,value,target,velocity * scale,)..tolerance = _kFlingTolerance;assert(simulation.type != SpringType.underDamped,'The specified spring simulation is of type SpringType.underDamped.\n'7 unmodified lines/// Drives the animation according to the given simulation.////// {@template flutter.animation.AnimationController.animateWith}/// The values from the simulation are clamped to the [lowerBound] and/// [upperBound]. To avoid this, consider creating the [AnimationController]/// using the [AnimationController.unbounded] constructor.3 unmodified lines/// The most recently returned [TickerFuture], if any, is marked as having been/// canceled, meaning the future never completes and its [TickerFuture.orCancel]/// derivative future completes with a [TickerCanceled] error./// {@endtemplate}////// The [status] is always [AnimationStatus.forward] for the entire duration/// of the simulation.////// See also:////// * [animateBackWith], which is like this method but the status is always/// [AnimationStatus.reverse].TickerFuture animateWith(Simulation simulation) {assert(_ticker != null,5 unmodified linesreturn _startSimulation(simulation);}/// Drives the animation according to the given simulation with a [status] of/// [AnimationStatus.reverse].////// {@macro flutter.animation.AnimationController.animateWith}////// The [status] is always [AnimationStatus.reverse] for the entire duration/// of the simulation.////// See also:////// * [animateWith], which is like this method but the status is always/// [AnimationStatus.forward].TickerFuture animateBackWith(Simulation simulation) {assert(_ticker != null,'AnimationController.animateWith() called after AnimationController.dispose()\n''AnimationController methods should not be used after calling dispose.',);stop();_direction = _AnimationDirection.reverse;return _startSimulation(simulation);}TickerFuture _startSimulation(Simulation simulation) {assert(!isAnimating);_simulation = simulation;_lastElapsedDuration = Duration.zero;_value = clampDouble(simulation.x(0.0), lowerBound, upperBound);final TickerFuture result = _ticker!.start();_status =(_direction == _AnimationDirection.forward)? AnimationStatus.forward: AnimationStatus.reverse;_checkStatusChanged();return result;}15 unmodified lines/// and which does send notifications./// * [forward], [reverse], [animateTo], [animateWith], [fling], and [repeat],/// which restart the animation controller.void stop({bool canceled = true}) {assert(_ticker != null,'AnimationController.stop() called after AnimationController.dispose()\n'26 unmodified lines}return true;}());assert(debugMaybeDispatchDisposed(this));_ticker!.dispose();_ticker = null;clearStatusListeners();12 unmodified linesvoid _tick(Duration elapsed) {_lastElapsedDuration = elapsed;final double elapsedInSeconds =elapsed.inMicroseconds.toDouble() / Duration.microsecondsPerSecond;assert(elapsedInSeconds >= 0.0);_value = clampDouble(_simulation!.x(elapsedInSeconds), lowerBound, upperBound);if (_simulation!.isDone(elapsedInSeconds)) {_status =(_direction == _AnimationDirection.forward)? AnimationStatus.completed: AnimationStatus.dismissed;stop(canceled: false);}notifyListeners();29 unmodified lines@overridedouble x(double timeInSeconds) {final double t = clampDouble(timeInSeconds / _durationInSeconds, 0.0, 1.0);return switch (t) {0.0 => _begin,1.0 => _end,_ => _begin + (_end - _begin) * _curve.transform(t),};}@override9 unmodified linestypedef _DirectionSetter = void Function(_AnimationDirection direction);class _RepeatingSimulation extends Simulation {_RepeatingSimulation(double initialValue,this.min,this.max,this.reverse,Duration period,this.directionSetter,this.count,) : assert(count == null || count > 0, 'Count shall be greater than zero if not null'),_periodInSeconds = period.inMicroseconds / Duration.microsecondsPerSecond,_initialT =(max == min)? 0.0: ((clampDouble(initialValue, min, max) - min) / (max - min)) *(period.inMicroseconds / Duration.microsecondsPerSecond) {assert(_periodInSeconds > 0.0);assert(_initialT >= 0.0);}1 unmodified linefinal double min;final double max;final bool reverse;final int? count;final _DirectionSetter directionSetter;final double _periodInSeconds;final double _initialT;late final double _exitTimeInSeconds = (count! * _periodInSeconds) - _initialT;@overridedouble x(double timeInSeconds) {assert(timeInSeconds >= 0.0);15 unmodified linesdouble dx(double timeInSeconds) => (max - min) / _periodInSeconds;@overridebool isDone(double timeInSeconds) {// if [timeInSeconds] elapsed the [_exitTimeInSeconds] && [count] is not null,// consider marking the simulation as "DONE"return count != null && (timeInSeconds >= _exitTimeInSeconds);}}
1 unmodified line2345675 unmodified lines1314151617183 unmodified lines22232425262728293031323334353647 unmodified lines848586878889909192939495969798991001011021031 unmodified line1051061071081091101 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'curves.dart';5 unmodified lines/// - [ExpansionTile]/// - [MaterialApp]/// - [PopupMenuButton]////// If [duration] and [reverseDuration] are set to [Duration.zero], the/// corresponding animation will be disabled.3 unmodified lines@immutableclass AnimationStyle with Diagnosticable {/// Creates an instance of Animation Style class.AnimationStyle({this.curve,this.duration,this.reverseCurve,this.reverseDuration,});/// Creates an instance of Animation Style class with no animation.static AnimationStyle noAnimation = AnimationStyle(duration: Duration.zero,reverseDuration: Duration.zero,);47 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is AnimationStyle&& other.curve == curve&& other.duration == duration&& other.reverseCurve == reverseCurve&& other.reverseDuration == reverseDuration;}@overrideint get hashCode => Object.hash(curve,duration,reverseCurve,reverseDuration,);@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {1 unmodified lineproperties.add(DiagnosticsProperty<Curve>('curve', curve, defaultValue: null));properties.add(DiagnosticsProperty<Duration>('duration', duration, defaultValue: null));properties.add(DiagnosticsProperty<Curve>('reverseCurve', reverseCurve, defaultValue: null));properties.add(DiagnosticsProperty<Duration>('reverseDuration', reverseDuration, defaultValue: null));}}1 unmodified line23456789105 unmodified lines1617181920212223243 unmodified lines2829303132333435363747 unmodified lines8586878889909192939495969798991 unmodified line1011021031041051061071081 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'package:flutter/foundation.dart';import 'curves.dart';5 unmodified lines/// - [ExpansionTile]/// - [MaterialApp]/// - [PopupMenuButton]/// - [ScaffoldMessengerState.showSnackBar]/// - [showBottomSheet]/// - [showModalBottomSheet]////// If [duration] and [reverseDuration] are set to [Duration.zero], the/// corresponding animation will be disabled.3 unmodified lines@immutableclass AnimationStyle with Diagnosticable {/// Creates an instance of Animation Style class.const AnimationStyle({this.curve, this.duration, this.reverseCurve, this.reverseDuration});/// Creates an instance of Animation Style class with no animation.static const AnimationStyle noAnimation = AnimationStyle(duration: Duration.zero,reverseDuration: Duration.zero,);47 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is AnimationStyle &&other.curve == curve &&other.duration == duration &&other.reverseCurve == reverseCurve &&other.reverseDuration == reverseDuration;}@overrideint get hashCode => Object.hash(curve, duration, reverseCurve, reverseDuration);@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {1 unmodified lineproperties.add(DiagnosticsProperty<Curve>('curve', curve, defaultValue: null));properties.add(DiagnosticsProperty<Duration>('duration', duration, defaultValue: null));properties.add(DiagnosticsProperty<Curve>('reverseCurve', reverseCurve, defaultValue: null));properties.add(DiagnosticsProperty<Duration>('reverseDuration', reverseDuration, defaultValue: null),);}}
1 unmodified line23456715 unmodified lines2324252627282930313233343536373816 unmodified lines5556575859606162636465666768697029 unmodified lines10010110210310410510610710810911011111211311411540 unmodified lines1561571581591601611626 unmodified lines16917017117217317417517689 unmodified lines26626726826927027127227334 unmodified lines30830931031131231331431558 unmodified lines37437537637737837938038138238338431 unmodified lines4164174184194204214224234244254264274284294302 unmodified lines43343443543643743858 unmodified lines4974984995005015025035044 unmodified lines50951051151251351446 unmodified lines56156256356456556656756856957057157222 unmodified lines59559659759859960025 unmodified lines62662762862963063163263363463563663763863923 unmodified lines66366466566666766866967067167267367426 unmodified lines70170270370470570670770870971016 unmodified lines7277287297307317327331 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;15 unmodified linesconst _AlwaysCompleteAnimation();@overridevoid addListener(VoidCallback listener) { }@overridevoid removeListener(VoidCallback listener) { }@overridevoid addStatusListener(AnimationStatusListener listener) { }@overridevoid removeStatusListener(AnimationStatusListener listener) { }@overrideAnimationStatus get status => AnimationStatus.completed;16 unmodified linesconst _AlwaysDismissedAnimation();@overridevoid addListener(VoidCallback listener) { }@overridevoid removeListener(VoidCallback listener) { }@overridevoid addStatusListener(AnimationStatusListener listener) { }@overridevoid removeStatusListener(AnimationStatusListener listener) { }@overrideAnimationStatus get status => AnimationStatus.dismissed;29 unmodified linesfinal T value;@overridevoid addListener(VoidCallback listener) { }@overridevoid removeListener(VoidCallback listener) { }@overridevoid addStatusListener(AnimationStatusListener listener) { }@overridevoid removeStatusListener(AnimationStatusListener listener) { }@overrideAnimationStatus get status => AnimationStatus.forward;40 unmodified lines/// Stops calling the listener every time the status of the animation changes.////// Listeners can be added with [addStatusListener].void removeStatusListener(AnimationStatusListener listener) => parent.removeStatusListener(listener);/// The current status of this animation.AnimationStatus get status => parent.status;6 unmodified lines/// object, and then later change the animation from which the proxy receives/// its value.class ProxyAnimation extends Animation<double>with AnimationLazyListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {/// Creates a proxy animation.////// If the animation argument is omitted, the proxy animation will have the89 unmodified lines/// * [CurvedAnimation], which can take separate curves for when the animation/// is going forward than for when it is going in reverse.class ReverseAnimation extends Animation<double>with AnimationLazyListenerMixin, AnimationLocalStatusListenersMixin {/// Creates a reverse animation.ReverseAnimation(this.parent);34 unmodified linesAnimationStatus _reverseStatus(AnimationStatus status) {return switch (status) {AnimationStatus.forward => AnimationStatus.reverse,AnimationStatus.reverse => AnimationStatus.forward,AnimationStatus.completed => AnimationStatus.dismissed,AnimationStatus.dismissed => AnimationStatus.completed,};58 unmodified lines/// [Curve].class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<double> {/// Creates a curved animation.CurvedAnimation({required this.parent,required this.curve,this.reverseCurve,}) {_updateCurveDirection(parent.status);parent.addStatusListener(_updateCurveDirection);}31 unmodified linesbool isDisposed = false;void _updateCurveDirection(AnimationStatus status) {switch (status) {case AnimationStatus.dismissed:case AnimationStatus.completed:_curveDirection = null;case AnimationStatus.forward:_curveDirection ??= AnimationStatus.forward;case AnimationStatus.reverse:_curveDirection ??= AnimationStatus.reverse;}}bool get _useForwardCurve {2 unmodified lines/// Cleans up any listeners added by this CurvedAnimation.void dispose() {isDisposed = true;parent.removeStatusListener(_updateCurveDirection);}58 unmodified lines/// removed, it exposes a [dispose()] method. Call this method to shut this/// object down.class TrainHoppingAnimation extends Animation<double>with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {/// Creates a train-hopping animation.////// The current train argument must not be null but the next train argument4 unmodified linesthis._nextTrain, {this.onSwitchedTrain,}) {if (_nextTrain != null) {if (_currentTrain!.value == _nextTrain!.value) {_currentTrain = _nextTrain;46 unmodified linesbool hop = false;if (_nextTrain != null) {assert(_mode != null);switch (_mode!) {case _TrainHoppingMode.minimize:hop = _nextTrain!.value <= _currentTrain!.value;case _TrainHoppingMode.maximize:hop = _nextTrain!.value >= _currentTrain!.value;}if (hop) {_currentTrain!..removeStatusListener(_statusChangeHandler)22 unmodified lines/// After this is called, this object is no longer usable.@overridevoid dispose() {assert(_currentTrain != null);_currentTrain!.removeStatusListener(_statusChangeHandler);_currentTrain!.removeListener(_valueChangeHandler);25 unmodified lines/// [next] animation if [next] is moving, and the status of the [first]/// animation otherwise.abstract class CompoundAnimation<T> extends Animation<T>with AnimationLazyListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {/// Creates a [CompoundAnimation].////// Either argument can be a [CompoundAnimation] itself to combine multiple animations.CompoundAnimation({required this.first,required this.next,});/// The first sub-animation. Its status takes precedence if neither are/// animating.23 unmodified lines/// The default is that if the [next] animation is moving, use its status./// Otherwise, default to [first].@overrideAnimationStatus get status {if (next.status == AnimationStatus.forward || next.status == AnimationStatus.reverse) {return next.status;}return first.status;}@overrideString toString() {26 unmodified lines/// of the values of the `left` and `right` animations.class AnimationMean extends CompoundAnimation<double> {/// Creates an animation that tracks the mean of two other animations.AnimationMean({required Animation<double> left,required Animation<double> right,}) : super(first: left, next: right);@overridedouble get value => (first.value + next.value) / 2.0;16 unmodified lines/// An animation that tracks the minimum of two other animations.////// The [value] of this animation is the maximum of the values of/// [first] and [next].class AnimationMin<T extends num> extends CompoundAnimation<T> {/// Creates an [AnimationMin].1 unmodified line2345678915 unmodified lines2526272829303132333435363738394016 unmodified lines5758596061626364656667686970717229 unmodified lines10210310410510610710810911011111211311411511611740 unmodified lines1581591601611621631641656 unmodified lines17217317417517617717817918018189 unmodified lines27127227327427527627734 unmodified lines31231331431531631731831958 unmodified lines37837938038138238338438531 unmodified lines4174184194204214224232 unmodified lines42642742842943043143258 unmodified lines4914924934944954964974984995004 unmodified lines50550650750850951051146 unmodified lines55855956056156256356456556656722 unmodified lines59059159259359459559625 unmodified lines62262362462562662762862963063163263363463523 unmodified lines65966066166266366466526 unmodified lines69269369469569669769869916 unmodified lines7167177187197207217221 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/widgets.dart';library;import 'dart:math' as math;15 unmodified linesconst _AlwaysCompleteAnimation();@overridevoid addListener(VoidCallback listener) {}@overridevoid removeListener(VoidCallback listener) {}@overridevoid addStatusListener(AnimationStatusListener listener) {}@overridevoid removeStatusListener(AnimationStatusListener listener) {}@overrideAnimationStatus get status => AnimationStatus.completed;16 unmodified linesconst _AlwaysDismissedAnimation();@overridevoid addListener(VoidCallback listener) {}@overridevoid removeListener(VoidCallback listener) {}@overridevoid addStatusListener(AnimationStatusListener listener) {}@overridevoid removeStatusListener(AnimationStatusListener listener) {}@overrideAnimationStatus get status => AnimationStatus.dismissed;29 unmodified linesfinal T value;@overridevoid addListener(VoidCallback listener) {}@overridevoid removeListener(VoidCallback listener) {}@overridevoid addStatusListener(AnimationStatusListener listener) {}@overridevoid removeStatusListener(AnimationStatusListener listener) {}@overrideAnimationStatus get status => AnimationStatus.forward;40 unmodified lines/// Stops calling the listener every time the status of the animation changes.////// Listeners can be added with [addStatusListener].void removeStatusListener(AnimationStatusListener listener) =>parent.removeStatusListener(listener);/// The current status of this animation.AnimationStatus get status => parent.status;6 unmodified lines/// object, and then later change the animation from which the proxy receives/// its value.class ProxyAnimation extends Animation<double>withAnimationLazyListenerMixin,AnimationLocalListenersMixin,AnimationLocalStatusListenersMixin {/// Creates a proxy animation.////// If the animation argument is omitted, the proxy animation will have the89 unmodified lines/// * [CurvedAnimation], which can take separate curves for when the animation/// is going forward than for when it is going in reverse.class ReverseAnimation extends Animation<double>with AnimationLazyListenerMixin, AnimationLocalStatusListenersMixin {/// Creates a reverse animation.ReverseAnimation(this.parent);34 unmodified linesAnimationStatus _reverseStatus(AnimationStatus status) {return switch (status) {AnimationStatus.forward => AnimationStatus.reverse,AnimationStatus.reverse => AnimationStatus.forward,AnimationStatus.completed => AnimationStatus.dismissed,AnimationStatus.dismissed => AnimationStatus.completed,};58 unmodified lines/// [Curve].class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<double> {/// Creates a curved animation.CurvedAnimation({required this.parent, required this.curve, this.reverseCurve}) {assert(debugMaybeDispatchCreated('animation', 'CurvedAnimation', this));_updateCurveDirection(parent.status);parent.addStatusListener(_updateCurveDirection);}31 unmodified linesbool isDisposed = false;void _updateCurveDirection(AnimationStatus status) {_curveDirection = status.isAnimating ? _curveDirection ?? status : null;}bool get _useForwardCurve {2 unmodified lines/// Cleans up any listeners added by this CurvedAnimation.void dispose() {assert(debugMaybeDispatchDisposed(this));isDisposed = true;parent.removeStatusListener(_updateCurveDirection);}58 unmodified lines/// removed, it exposes a [dispose()] method. Call this method to shut this/// object down.class TrainHoppingAnimation extends Animation<double>withAnimationEagerListenerMixin,AnimationLocalListenersMixin,AnimationLocalStatusListenersMixin {/// Creates a train-hopping animation.////// The current train argument must not be null but the next train argument4 unmodified linesthis._nextTrain, {this.onSwitchedTrain,}) {assert(debugMaybeDispatchCreated('animation', 'TrainHoppingAnimation', this));if (_nextTrain != null) {if (_currentTrain!.value == _nextTrain!.value) {_currentTrain = _nextTrain;46 unmodified linesbool hop = false;if (_nextTrain != null) {assert(_mode != null);hop = switch (_mode!) {_TrainHoppingMode.minimize => _nextTrain!.value <= _currentTrain!.value,_TrainHoppingMode.maximize => _nextTrain!.value >= _currentTrain!.value,};if (hop) {_currentTrain!..removeStatusListener(_statusChangeHandler)22 unmodified lines/// After this is called, this object is no longer usable.@overridevoid dispose() {assert(debugMaybeDispatchDisposed(this));assert(_currentTrain != null);_currentTrain!.removeStatusListener(_statusChangeHandler);_currentTrain!.removeListener(_valueChangeHandler);25 unmodified lines/// [next] animation if [next] is moving, and the status of the [first]/// animation otherwise.abstract class CompoundAnimation<T> extends Animation<T>withAnimationLazyListenerMixin,AnimationLocalListenersMixin,AnimationLocalStatusListenersMixin {/// Creates a [CompoundAnimation].////// Either argument can be a [CompoundAnimation] itself to combine multiple animations.CompoundAnimation({required this.first, required this.next});/// The first sub-animation. Its status takes precedence if neither are/// animating.23 unmodified lines/// The default is that if the [next] animation is moving, use its status./// Otherwise, default to [first].@overrideAnimationStatus get status => next.status.isAnimating ? next.status : first.status;@overrideString toString() {26 unmodified lines/// of the values of the `left` and `right` animations.class AnimationMean extends CompoundAnimation<double> {/// Creates an animation that tracks the mean of two other animations.AnimationMean({required Animation<double> left, required Animation<double> right}): super(first: left, next: right);@overridedouble get value => (first.value + next.value) / 2.0;16 unmodified lines/// An animation that tracks the minimum of two other animations.////// The [value] of this animation is the minimum of the values of/// [first] and [next].class AnimationMin<T extends num> extends CompoundAnimation<T> {/// Creates an [AnimationMin].
1 unmodified line234567147 unmodified lines15515615715815916016131 unmodified lines193194195196197198126 unmodified lines32532632732832933033133233388 unmodified lines42242342442542642742842943043143243343443543643743843991 unmodified lines531532533534535536537538539540541542113 unmodified lines6566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916924 unmodified lines6976986997007017027037047057067077087097107117127137147154 unmodified lines7207217227237247257267277287297304 unmodified lines7357367377387397407411 unmodified line74374474574674774874975021 unmodified lines77277377477577677777823 unmodified lines80280380480580680780880981081141 unmodified lines853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884126 unmodified lines101110121013101410151016101710181019138 unmodified lines115811591160116111621163116456 unmodified lines122112221223122412251226122784 unmodified lines1312131313141315131613171318355 unmodified lines1674167516761677167816791680168116821 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;import 'dart:ui';147 unmodified lines/// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_interval.mp4}class Interval extends Curve {/// Creates an interval curve.const Interval(this.begin, this.end, { this.curve = Curves.linear });/// The largest value for which this interval is 0.0.///31 unmodified lines}}/// A curve that is 0.0 until it hits the threshold, then it jumps to 1.0.////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_threshold.mp4}126 unmodified linesstatic const double _cubicErrorBound = 0.001;double _evaluateCubic(double a, double b, double m) {return 3 * a * (1 - m) * (1 - m) * m +3 * b * (1 - m) * m * m +m * m * m;}@override88 unmodified linesfinal double scaledT = (t - (firstCurve ? 0.0 : midpoint.dx)) / scaleX;if (firstCurve) {return Cubic(a1.dx / scaleX,a1.dy / scaleY,b1.dx / scaleX,b1.dy / scaleY,).transform(scaledT) * scaleY;} else {return Cubic((a2.dx - midpoint.dx) / scaleX,(a2.dy - midpoint.dy) / scaleY,(b2.dx - midpoint.dx) / scaleX,(b2.dy - midpoint.dy) / scaleY,).transform(scaledT) * scaleY + midpoint.dy;}}91 unmodified linessample(r, q);}}// If the curve starts and ends on the same point, then we force it to// subdivide at least once, because otherwise it will terminate immediately.sample(first,last,forceSubdivide: (first.value.dx - last.value.dx).abs() < tolerance && (first.value.dy - last.value.dy).abs() < tolerance,);return samples;}113 unmodified lines/// [transform] is called. If you would rather pre-compute the structures,/// use [CatmullRomSpline.precompute] instead.CatmullRomSpline(List<Offset> controlPoints, {double tension = 0.0,Offset? startHandle,Offset? endHandle,}) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'),assert(tension >= 0.0, 'tension $tension must not be negative.'),assert(controlPoints.length > 3, 'There must be at least four control points to create a CatmullRomSpline.'),_controlPoints = controlPoints,_startHandle = startHandle,_endHandle = endHandle,_tension = tension,_cubicSegments = <List<Offset>>[];/// Constructs a centripetal Catmull-Rom spline curve.////// The same as [CatmullRomSpline.new], except that the internal data/// structures are precomputed instead of being computed lazily.CatmullRomSpline.precompute(List<Offset> controlPoints, {double tension = 0.0,Offset? startHandle,Offset? endHandle,}) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'),assert(tension >= 0.0, 'tension $tension must not be negative.'),assert(controlPoints.length > 3, 'There must be at least four control points to create a CatmullRomSpline.'),_controlPoints = null,_startHandle = null,_endHandle = null,_tension = null,_cubicSegments = _computeSegments(controlPoints, tension, startHandle: startHandle, endHandle: endHandle);static List<List<Offset>> _computeSegments(List<Offset> controlPoints,4 unmodified linesassert(startHandle == null || startHandle.isFinite,'The provided startHandle of CatmullRomSpline must be finite. The ''startHandle given was $startHandle.');assert(endHandle == null || endHandle.isFinite,'The provided endHandle of CatmullRomSpline must be finite. The endHandle ''given was $endHandle.');assert(() {for (int index = 0; index < controlPoints.length; index++) {if (!controlPoints[index].isFinite) {throw FlutterError('The provided CatmullRomSpline control point at index $index is not ''finite. The control point given was ${controlPoints[index]}.');}}4 unmodified lines// extend the first and last segments, respectively.startHandle ??= controlPoints[0] * 2.0 - controlPoints[1];endHandle ??= controlPoints.last * 2.0 - controlPoints[controlPoints.length - 2];final List<Offset> allPoints = <Offset>[startHandle,...controlPoints,endHandle,];// An alpha of 0.5 is what makes it a centripetal Catmull-Rom spline. A// value of 0.0 would make it a uniform Catmull-Rom spline, and a value of4 unmodified linesfinal double reverseTension = 1.0 - tension;final List<List<Offset>> result = <List<Offset>>[];for (int i = 0; i < allPoints.length - 3; ++i) {final List<Offset> curve = <Offset>[allPoints[i], allPoints[i + 1], allPoints[i + 2], allPoints[i + 3]];final Offset diffCurve10 = curve[1] - curve[0];final Offset diffCurve21 = curve[2] - curve[1];final Offset diffCurve32 = curve[3] - curve[2];1 unmodified linefinal double t12 = math.pow(diffCurve21.distance, alpha).toDouble();final double t23 = math.pow(diffCurve32.distance, alpha).toDouble();final Offset m1 = (diffCurve21 + (diffCurve10 / t01 - (curve[2] - curve[0]) / (t01 + t12)) * t12) * reverseTension;final Offset m2 = (diffCurve21 + (diffCurve32 / t23 - (curve[3] - curve[1]) / (t12 + t23)) * t12) * reverseTension;final Offset sumM12 = m1 + m2;final List<Offset> segment = <Offset>[21 unmodified linesreturn;}_cubicSegments.addAll(_computeSegments(_controlPoints!, _tension!, startHandle: _startHandle, endHandle: _endHandle),);}23 unmodified lines}final List<Offset> cubicControlPoints = _cubicSegments[index];final double localT2 = localT * localT;return cubicControlPoints[0] * localT2 * localT+ cubicControlPoints[1] * localT2+ cubicControlPoints[2] * localT+ cubicControlPoints[3];}}41 unmodified lines////// * This [paper on using Catmull-Rom splines](http://faculty.cs.tamu.edu/schaefer/research/cr_cad.pdf).CatmullRomCurve(this.controlPoints, {this.tension = 0.0}): assert(() {return validateControlPoints(controlPoints,tension: tension,reasons: _debugAssertReasons..clear(),);}(), 'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}'),// Pre-compute samples so that we don't have to evaluate the spline's inverse// all the time in transformInternal._precomputedSamples = <Curve2DSample>[];/// Constructs a centripetal [CatmullRomCurve].////// Same as [CatmullRomCurve.new], but it precomputes the internal curve data/// structures for a more predictable computation load.CatmullRomCurve.precompute(this.controlPoints, {this.tension = 0.0}): assert(() {return validateControlPoints(controlPoints,tension: tension,reasons: _debugAssertReasons..clear(),);}(), 'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}'),// Pre-compute samples so that we don't have to evaluate the spline's inverse// all the time in transformInternal._precomputedSamples = _computeSamples(controlPoints, tension);static List<Curve2DSample> _computeSamples(List<Offset> controlPoints, double tension) {return CatmullRomSpline.precompute(126 unmodified linesfinal double start = testSpline.findInverse(0.0);final double end = testSpline.findInverse(1.0);final Iterable<Curve2DSample> samplePoints = testSpline.generateSamples(start: start, end: end);/// If the first and last points in the samples aren't at (0,0) or (1,1)/// respectively, then the curve is multi-valued at the ends.if (samplePoints.first.value.dy.abs() > tolerance || (1.0 - samplePoints.last.value.dy).abs() > tolerance) {bool bail = true;success = false;assert(() {138 unmodified lines@overridedouble transformInternal(double t) {// Intended to match the behavior of:// https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/animation/DecelerateInterpolator.java// ...as of December 2016.t = 1.0 - t;return 1.0 - t * t;56 unmodified lines}}// ELASTIC CURVES/// An oscillating curve that grows in magnitude while overshooting its bounds.84 unmodified lines}}// PREDEFINED CURVES/// A collection of common animation curves.355 unmodified lines////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic_emphasized.mp4}static const ThreePointCubic easeInOutCubicEmphasized = ThreePointCubic(Offset(0.05, 0), Offset(0.133333, 0.06),Offset(0.166666, 0.4),Offset(0.208333, 0.82), Offset(0.25, 1),);/// A cubic animation curve that starts slowly, speeds up, and then ends1 unmodified line23456789147 unmodified lines15715815916016116216331 unmodified lines195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269126 unmodified lines39639739839940040140288 unmodified lines49149249349449549649749849950050150250350450550650750850951051191 unmodified lines603604605606607608609610611612613614615616617113 unmodified lines7317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767774 unmodified lines7827837847857867877887897907917927937947957967977987998004 unmodified lines8058068078088098108114 unmodified lines8168178188198208218228238248258268271 unmodified line82983083183283383483583683783883984021 unmodified lines86286386486586686786886987087187287323 unmodified lines89789889990090190290390490590641 unmodified lines948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985126 unmodified lines11121113111411151116111711181119112011211122138 unmodified lines126112621263126412651266126756 unmodified lines13241325132613271328132984 unmodified lines141414151416141714181419355 unmodified lines177517761777177817791780178117821783178417851 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'dart:math' as math;import 'dart:ui';147 unmodified lines/// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_interval.mp4}class Interval extends Curve {/// Creates an interval curve.const Interval(this.begin, this.end, {this.curve = Curves.linear});/// The largest value for which this interval is 0.0.///31 unmodified lines}}/// A curve that progresses according to [beginCurve] until [split], then/// according to [endCurve].////// Split curves are useful in situations where a widget must track the/// user's finger (which requires a linear animation), but can also be flung/// using a curve specified with the [endCurve] argument, after the finger is/// released. In such a case, the value of [split] would be the progress/// of the animation at the time when the finger was released.////// For example, if [split] is set to 0.5, [beginCurve] is [Curves.linear],/// and [endCurve] is [Curves.easeOutCubic], then the bottom-left quarter of the/// curve will be a straight line, and the top-right quarter will contain the/// entire [Curves.easeOutCubic] curve.////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_split.mp4}class Split extends Curve {/// Creates a split curve.const Split(this.split, {this.beginCurve = Curves.linear, this.endCurve = Curves.easeOutCubic});/// The progress value separating [beginCurve] from [endCurve].////// The value before which the curve progresses according to [beginCurve] and/// after which the curve progresses according to [endCurve].////// When t is exactly `split`, the curve has the value `split`.////// Must be between 0 and 1.0, inclusively.final double split;/// The curve to use before [split] is reached.////// Defaults to [Curves.linear].final Curve beginCurve;/// The curve to use after [split] is reached.////// Defaults to [Curves.easeOutCubic].final Curve endCurve;@overridedouble transform(double t) {assert(t >= 0.0 && t <= 1.0);assert(split >= 0.0 && split <= 1.0);if (t == 0.0 || t == 1.0) {return t;}if (t == split) {return split;}if (t < split) {final double curveProgress = t / split;final double transformed = beginCurve.transform(curveProgress);return lerpDouble(0, split, transformed)!;} else {final double curveProgress = (t - split) / (1 - split);final double transformed = endCurve.transform(curveProgress);return lerpDouble(split, 1, transformed)!;}}@overrideString toString() {return '${describeIdentity(this)}($split, $beginCurve, $endCurve)';}}/// A curve that is 0.0 until it hits the threshold, then it jumps to 1.0.////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_threshold.mp4}126 unmodified linesstatic const double _cubicErrorBound = 0.001;double _evaluateCubic(double a, double b, double m) {return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m;}@override88 unmodified linesfinal double scaledT = (t - (firstCurve ? 0.0 : midpoint.dx)) / scaleX;if (firstCurve) {return Cubic(a1.dx / scaleX,a1.dy / scaleY,b1.dx / scaleX,b1.dy / scaleY,).transform(scaledT) *scaleY;} else {return Cubic((a2.dx - midpoint.dx) / scaleX,(a2.dy - midpoint.dy) / scaleY,(b2.dx - midpoint.dx) / scaleX,(b2.dy - midpoint.dy) / scaleY,).transform(scaledT) *scaleY +midpoint.dy;}}91 unmodified linessample(r, q);}}// If the curve starts and ends on the same point, then we force it to// subdivide at least once, because otherwise it will terminate immediately.sample(first,last,forceSubdivide:(first.value.dx - last.value.dx).abs() < tolerance &&(first.value.dy - last.value.dy).abs() < tolerance,);return samples;}113 unmodified lines/// [transform] is called. If you would rather pre-compute the structures,/// use [CatmullRomSpline.precompute] instead.CatmullRomSpline(List<Offset> controlPoints, {double tension = 0.0,Offset? startHandle,Offset? endHandle,}) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'),assert(tension >= 0.0, 'tension $tension must not be negative.'),assert(controlPoints.length > 3,'There must be at least four control points to create a CatmullRomSpline.',),_controlPoints = controlPoints,_startHandle = startHandle,_endHandle = endHandle,_tension = tension,_cubicSegments = <List<Offset>>[];/// Constructs a centripetal Catmull-Rom spline curve.////// The same as [CatmullRomSpline.new], except that the internal data/// structures are precomputed instead of being computed lazily.CatmullRomSpline.precompute(List<Offset> controlPoints, {double tension = 0.0,Offset? startHandle,Offset? endHandle,}) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'),assert(tension >= 0.0, 'tension $tension must not be negative.'),assert(controlPoints.length > 3,'There must be at least four control points to create a CatmullRomSpline.',),_controlPoints = null,_startHandle = null,_endHandle = null,_tension = null,_cubicSegments = _computeSegments(controlPoints,tension,startHandle: startHandle,endHandle: endHandle,);static List<List<Offset>> _computeSegments(List<Offset> controlPoints,4 unmodified linesassert(startHandle == null || startHandle.isFinite,'The provided startHandle of CatmullRomSpline must be finite. The ''startHandle given was $startHandle.',);assert(endHandle == null || endHandle.isFinite,'The provided endHandle of CatmullRomSpline must be finite. The endHandle ''given was $endHandle.',);assert(() {for (int index = 0; index < controlPoints.length; index++) {if (!controlPoints[index].isFinite) {throw FlutterError('The provided CatmullRomSpline control point at index $index is not ''finite. The control point given was ${controlPoints[index]}.',);}}4 unmodified lines// extend the first and last segments, respectively.startHandle ??= controlPoints[0] * 2.0 - controlPoints[1];endHandle ??= controlPoints.last * 2.0 - controlPoints[controlPoints.length - 2];final List<Offset> allPoints = <Offset>[startHandle, ...controlPoints, endHandle];// An alpha of 0.5 is what makes it a centripetal Catmull-Rom spline. A// value of 0.0 would make it a uniform Catmull-Rom spline, and a value of4 unmodified linesfinal double reverseTension = 1.0 - tension;final List<List<Offset>> result = <List<Offset>>[];for (int i = 0; i < allPoints.length - 3; ++i) {final List<Offset> curve = <Offset>[allPoints[i],allPoints[i + 1],allPoints[i + 2],allPoints[i + 3],];final Offset diffCurve10 = curve[1] - curve[0];final Offset diffCurve21 = curve[2] - curve[1];final Offset diffCurve32 = curve[3] - curve[2];1 unmodified linefinal double t12 = math.pow(diffCurve21.distance, alpha).toDouble();final double t23 = math.pow(diffCurve32.distance, alpha).toDouble();final Offset m1 =(diffCurve21 + (diffCurve10 / t01 - (curve[2] - curve[0]) / (t01 + t12)) * t12) *reverseTension;final Offset m2 =(diffCurve21 + (diffCurve32 / t23 - (curve[3] - curve[1]) / (t12 + t23)) * t12) *reverseTension;final Offset sumM12 = m1 + m2;final List<Offset> segment = <Offset>[21 unmodified linesreturn;}_cubicSegments.addAll(_computeSegments(_controlPoints!,_tension!,startHandle: _startHandle,endHandle: _endHandle,),);}23 unmodified lines}final List<Offset> cubicControlPoints = _cubicSegments[index];final double localT2 = localT * localT;return cubicControlPoints[0] * localT2 * localT +cubicControlPoints[1] * localT2 +cubicControlPoints[2] * localT +cubicControlPoints[3];}}41 unmodified lines////// * This [paper on using Catmull-Rom splines](http://faculty.cs.tamu.edu/schaefer/research/cr_cad.pdf).CatmullRomCurve(this.controlPoints, {this.tension = 0.0}): assert(() {return validateControlPoints(controlPoints,tension: tension,reasons: _debugAssertReasons..clear(),);}(),'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}',),// Pre-compute samples so that we don't have to evaluate the spline's inverse// all the time in transformInternal._precomputedSamples = <Curve2DSample>[];/// Constructs a centripetal [CatmullRomCurve].////// Same as [CatmullRomCurve.new], but it precomputes the internal curve data/// structures for a more predictable computation load.CatmullRomCurve.precompute(this.controlPoints, {this.tension = 0.0}): assert(() {return validateControlPoints(controlPoints,tension: tension,reasons: _debugAssertReasons..clear(),);}(),'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}',),// Pre-compute samples so that we don't have to evaluate the spline's inverse// all the time in transformInternal._precomputedSamples = _computeSamples(controlPoints, tension);static List<Curve2DSample> _computeSamples(List<Offset> controlPoints, double tension) {return CatmullRomSpline.precompute(126 unmodified linesfinal double start = testSpline.findInverse(0.0);final double end = testSpline.findInverse(1.0);final Iterable<Curve2DSample> samplePoints = testSpline.generateSamples(start: start, end: end);/// If the first and last points in the samples aren't at (0,0) or (1,1)/// respectively, then the curve is multi-valued at the ends.if (samplePoints.first.value.dy.abs() > tolerance ||(1.0 - samplePoints.last.value.dy).abs() > tolerance) {bool bail = true;success = false;assert(() {138 unmodified lines@overridedouble transformInternal(double t) {// Intended to match the behavior of:// https://android.googlesource.com/platform/frameworks/base/+/main/core/java/android/view/animation/DecelerateInterpolator.java// ...as of December 2016.t = 1.0 - t;return 1.0 - t * t;56 unmodified lines}}// ELASTIC CURVES/// An oscillating curve that grows in magnitude while overshooting its bounds.84 unmodified lines}}// PREDEFINED CURVES/// A collection of common animation curves.355 unmodified lines////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic_emphasized.mp4}static const ThreePointCubic easeInOutCubicEmphasized = ThreePointCubic(Offset(0.05, 0),Offset(0.133333, 0.06),Offset(0.166666, 0.4),Offset(0.208333, 0.82),Offset(0.25, 1),);/// A cubic animation curve that starts slowly, speeds up, and then ends
1 unmodified line234567863 unmodified lines727374757677787980818283848586873 unmodified lines9192939495969749 unmodified lines1471481491501511521531541551561571581591 unmodified line1611621631641651661671681691701711721737 unmodified lines18118218318418518618754 unmodified lines2422432442452462472482492502512522532542552562572582592602612622631 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'animation.dart';63 unmodified linesmixin AnimationEagerListenerMixin {/// This implementation ignores listener registrations.@protectedvoid didRegisterListener() { }/// This implementation ignores listener registrations.@protectedvoid didUnregisterListener() { }/// Release the resources used by this object. The object is no longer usable/// after this method is called.@mustCallSupervoid dispose() { }}/// A mixin that implements the [addListener]/[removeListener] protocol and notifies3 unmodified lines/// and [didUnregisterListener]. Implementations of these methods can be obtained/// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin].mixin AnimationLocalListenersMixin {final ObserverList<VoidCallback> _listeners = ObserverList<VoidCallback>();/// Called immediately before a listener is added via [addListener].///49 unmodified linesfor (final VoidCallback listener in localListeners) {InformationCollector? collector;assert(() {collector = () => <DiagnosticsNode>[DiagnosticsProperty<AnimationLocalListenersMixin>('The $runtimeType notifying listeners was',this,style: DiagnosticsTreeStyle.errorProperty,),];return true;}());try {1 unmodified linelistener();}} catch (exception, stack) {FlutterError.reportError(FlutterErrorDetails(exception: exception,stack: stack,library: 'animation library',context: ErrorDescription('while notifying listeners for $runtimeType'),informationCollector: collector,));}}}7 unmodified lines/// and [didUnregisterListener]. Implementations of these methods can be obtained/// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin].mixin AnimationLocalStatusListenersMixin {final ObserverList<AnimationStatusListener> _statusListeners = ObserverList<AnimationStatusListener>();/// Called immediately before a status listener is added via [addStatusListener].///54 unmodified lines} catch (exception, stack) {InformationCollector? collector;assert(() {collector = () => <DiagnosticsNode>[DiagnosticsProperty<AnimationLocalStatusListenersMixin>('The $runtimeType notifying status listeners was',this,style: DiagnosticsTreeStyle.errorProperty,),];return true;}());FlutterError.reportError(FlutterErrorDetails(exception: exception,stack: stack,library: 'animation library',context: ErrorDescription('while notifying status listeners for $runtimeType'),informationCollector: collector,));}}}1 unmodified line23456763 unmodified lines717273747576777879808182838485863 unmodified lines9091929394959649 unmodified lines1461471481491501511521531541551561571581591 unmodified line1611621631641651661671681691701711721731741757 unmodified lines18318418518618718818919054 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682691 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'animation.dart';63 unmodified linesmixin AnimationEagerListenerMixin {/// This implementation ignores listener registrations.@protectedvoid didRegisterListener() {}/// This implementation ignores listener registrations.@protectedvoid didUnregisterListener() {}/// Release the resources used by this object. The object is no longer usable/// after this method is called.@mustCallSupervoid dispose() {}}/// A mixin that implements the [addListener]/[removeListener] protocol and notifies3 unmodified lines/// and [didUnregisterListener]. Implementations of these methods can be obtained/// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin].mixin AnimationLocalListenersMixin {final HashedObserverList<VoidCallback> _listeners = HashedObserverList<VoidCallback>();/// Called immediately before a listener is added via [addListener].///49 unmodified linesfor (final VoidCallback listener in localListeners) {InformationCollector? collector;assert(() {collector =() => <DiagnosticsNode>[DiagnosticsProperty<AnimationLocalListenersMixin>('The $runtimeType notifying listeners was',this,style: DiagnosticsTreeStyle.errorProperty,),];return true;}());try {1 unmodified linelistener();}} catch (exception, stack) {FlutterError.reportError(FlutterErrorDetails(exception: exception,stack: stack,library: 'animation library',context: ErrorDescription('while notifying listeners for $runtimeType'),informationCollector: collector,),);}}}7 unmodified lines/// and [didUnregisterListener]. Implementations of these methods can be obtained/// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin].mixin AnimationLocalStatusListenersMixin {final ObserverList<AnimationStatusListener> _statusListeners =ObserverList<AnimationStatusListener>();/// Called immediately before a status listener is added via [addStatusListener].///54 unmodified lines} catch (exception, stack) {InformationCollector? collector;assert(() {collector =() => <DiagnosticsNode>[DiagnosticsProperty<AnimationLocalStatusListenersMixin>('The $runtimeType notifying status listeners was',this,style: DiagnosticsTreeStyle.errorProperty,),];return true;}());FlutterError.reportError(FlutterErrorDetails(exception: exception,stack: stack,library: 'animation library',context: ErrorDescription('while notifying status listeners for $runtimeType'),informationCollector: collector,),);}}}
1 unmodified line23456713 unmodified lines2122232425262754 unmodified lines82838485868788899058 unmodified lines149150151152153154155156157158159100 unmodified lines26026126226326426526626726826999 unmodified lines36937037137237337437537625 unmodified lines40240340440540640740813 unmodified lines42242342442542642742814 unmodified lines44344444544644744844920 unmodified lines47047147247347447547621 unmodified lines49849950050150250350442 unmodified lines5475485495505515525531 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:ui' show Color, Rect, Size;import 'package:flutter/foundation.dart';13 unmodified lines/// from a callback.typedef AnimatableCallback<T> = T Function(double value);/// An object that can produce a value of type `T` given an [Animation<double>]/// as input.////// Typically, the values of the input animation are nominally in the range 0.054 unmodified lines}/// Returns a new [Animatable] whose value is determined by first evaluating/// the given parent and then evaluating this object.////// This allows [Tween]s to be chained before obtaining an [Animation].Animatable<T> chain(Animatable<double> parent) {return _ChainedEvaluation<T>(parent, this);}58 unmodified lines/// [animate] method and pass it the [Animation] object that you want to/// modify.////// You can chain [Tween] objects together using the [chain] method, so that a/// single [Animation] object is configured by multiple [Tween] objects called/// in succession. This is different than calling the [animate] method twice,/// which results in two separate [Animation] objects, each configured with a/// single [Tween].////// {@tool snippet}///100 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.Tween({this.begin,this.end,});/// The value this variable has at the beginning of the animation.///99 unmodified lines/// A [Tween] that evaluates its [parent] in reverse.class ReverseTween<T extends Object?> extends Tween<T> {/// Construct a [Tween] that evaluates its [parent] in reverse.ReverseTween(this.parent): super(begin: parent.end, end: parent.begin);/// This tween's value is the same as the parent's value evaluated in reverse.///25 unmodified lines/// or [end] if you want the effect of fading in or out of transparent./// Instead prefer null. [Colors.transparent] refers to black transparent and/// thus will fade out of or into black which is likely unwanted.ColorTween({ super.begin, super.end });/// Returns the value this variable has at the given animation clock value.@override13 unmodified lines////// The [begin] and [end] properties may be null; the null value/// is treated as an empty size.SizeTween({ super.begin, super.end });/// Returns the value this variable has at the given animation clock value.@override14 unmodified lines////// The [begin] and [end] properties may be null; the null value/// is treated as an empty rect at the top left corner.RectTween({ super.begin, super.end });/// Returns the value this variable has at the given animation clock value.@override20 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.IntTween({ super.begin, super.end });// The inherited lerp() function doesn't work with ints because it multiplies// the begin and end types by a double, and int * double returns a double.21 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.StepTween({ super.begin, super.end });// The inherited lerp() function doesn't work with ints because it multiplies// the begin and end types by a double, and int * double returns a double.42 unmodified lines/// [AnimationController].class CurveTween extends Animatable<double> {/// Creates a curve tween.CurveTween({ required this.curve });/// The curve to use when transforming the value of the animation.Curve curve;1 unmodified line234567891013 unmodified lines2425262728293054 unmodified lines85868788899091929394959697989958 unmodified lines158159160161162163164165166167168169100 unmodified lines27027127227327427527699 unmodified lines37637737837938038138225 unmodified lines40840941041141241341413 unmodified lines42842943043143243343414 unmodified lines44945045145245345445520 unmodified lines47647747847948048148221 unmodified lines50450550650750850951042 unmodified lines5535545555565575585591 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'dart:ui' show Color, Rect, Size;import 'package:flutter/foundation.dart';13 unmodified lines/// from a callback.typedef AnimatableCallback<T> = T Function(double value);/// An object that can produce a value of type [T] given an [Animation<double>]/// as input.////// Typically, the values of the input animation are nominally in the range 0.054 unmodified lines}/// Returns a new [Animatable] whose value is determined by first evaluating/// the given parent and then evaluating this object at the result.////// This method represents function composition on [transform]:/// the [transform] method of the returned [Animatable] is the result of/// composing this object's [transform] method with/// the given parent's [transform] method.////// This allows [Tween]s to be chained before obtaining an [Animation],/// without allocating an [Animation] for the intermediate result.Animatable<T> chain(Animatable<double> parent) {return _ChainedEvaluation<T>(parent, this);}58 unmodified lines/// [animate] method and pass it the [Animation] object that you want to/// modify.////// You can chain [Tween] objects together using the [chain] method,/// producing the function composition of their [transform] methods./// Configuring a single [Animation] object by calling [animate] on the/// resulting [Tween] produces the same result as calling the [animate] method/// on each [Tween] separately in succession, but more efficiently because/// it avoids creating [Animation] objects for the intermediate results.////// {@tool snippet}///100 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.Tween({this.begin, this.end});/// The value this variable has at the beginning of the animation.///99 unmodified lines/// A [Tween] that evaluates its [parent] in reverse.class ReverseTween<T extends Object?> extends Tween<T> {/// Construct a [Tween] that evaluates its [parent] in reverse.ReverseTween(this.parent) : super(begin: parent.end, end: parent.begin);/// This tween's value is the same as the parent's value evaluated in reverse.///25 unmodified lines/// or [end] if you want the effect of fading in or out of transparent./// Instead prefer null. [Colors.transparent] refers to black transparent and/// thus will fade out of or into black which is likely unwanted.ColorTween({super.begin, super.end});/// Returns the value this variable has at the given animation clock value.@override13 unmodified lines////// The [begin] and [end] properties may be null; the null value/// is treated as an empty size.SizeTween({super.begin, super.end});/// Returns the value this variable has at the given animation clock value.@override14 unmodified lines////// The [begin] and [end] properties may be null; the null value/// is treated as an empty rect at the top left corner.RectTween({super.begin, super.end});/// Returns the value this variable has at the given animation clock value.@override20 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.IntTween({super.begin, super.end});// The inherited lerp() function doesn't work with ints because it multiplies// the begin and end types by a double, and int * double returns a double.21 unmodified lines/// The [begin] and [end] properties must be non-null before the tween is/// first used, but the arguments can be null if the values are going to be/// filled in later.StepTween({super.begin, super.end});// The inherited lerp() function doesn't work with ints because it multiplies// the begin and end types by a double, and int * double returns a double.42 unmodified lines/// [AnimationController].class CurveTween extends Animatable<double> {/// Creates a curve tween.CurveTween({required this.curve});/// The curve to use when transforming the value of the animation.Curve curve;
49 unmodified lines505152535455565765 unmodified lines12312412512612712812913013113249 unmodified lines/// There's a small cost associated with building a [TweenSequence] so it's/// best to reuse one, rather than rebuilding it on every frame, when that's/// possible.TweenSequence(List<TweenSequenceItem<T>> items): assert(items.isNotEmpty) {_items.addAll(items);double totalWeight = 0.0;65 unmodified lines/// Construct a TweenSequenceItem.////// The [weight] must be greater than 0.0.const TweenSequenceItem({required this.tween,required this.weight,}) : assert(weight > 0.0);/// Defines the value of the [TweenSequence] for the interval within the/// animation's duration indicated by [weight] and this item's position49 unmodified lines5051525354555665 unmodified lines12212312412512612712849 unmodified lines/// There's a small cost associated with building a [TweenSequence] so it's/// best to reuse one, rather than rebuilding it on every frame, when that's/// possible.TweenSequence(List<TweenSequenceItem<T>> items) : assert(items.isNotEmpty) {_items.addAll(items);double totalWeight = 0.0;65 unmodified lines/// Construct a TweenSequenceItem.////// The [weight] must be greater than 0.0.const TweenSequenceItem({required this.tween, required this.weight}) : assert(weight > 0.0);/// Defines the value of the [TweenSequence] for the interval within the/// animation's duration indicated by [weight] and this item's position
27 unmodified lines282930313233341 unmodified line36373839404142436 unmodified lines5051525354555657585929 unmodified lines8990919293949596979839 unmodified lines1381391401411421431441451461471481491501511521534 unmodified lines15815916016116216316416516616716816917017117214 unmodified lines18718818919019119219319427 unmodified lines////// See also:////// * <https://developer.apple.com/ios/human-interface-guidelines/controls/progress-indicators/#activity-indicators>class CupertinoActivityIndicator extends StatefulWidget {/// Creates an iOS-style activity indicator that spins clockwise.const CupertinoActivityIndicator({1 unmodified linethis.color,this.animating = true,this.radius = _kDefaultIndicatorRadius,}) : assert(radius > 0.0),progress = 1.0;/// Creates a non-animated iOS-style activity indicator that displays/// a partial count of ticks based on the value of [progress].6 unmodified linesthis.color,this.radius = _kDefaultIndicatorRadius,this.progress = 1.0,}) : assert(radius > 0.0),assert(progress >= 0.0),assert(progress <= 1.0),animating = false;/// Color of the activity indicator.///29 unmodified lines@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1),vsync: this,);if (widget.animating) {_controller.repeat();39 unmodified lines/// Alpha values extracted from the native component (for both dark and light mode) to/// draw the spinning ticks.const List<int> _kAlphaValues = <int>[47,47,47,47,72,97,122,147,];/// The alpha value that is used to draw the partially revealed ticks.const int _partiallyRevealedAlpha = 147;4 unmodified linesrequired this.activeColor,required this.radius,required this.progress,}) : tickFundamentalRRect = RRect.fromLTRBXY(-radius / _kDefaultIndicatorRadius,-radius / 3.0,radius / _kDefaultIndicatorRadius,-radius,radius / _kDefaultIndicatorRadius,radius / _kDefaultIndicatorRadius,),super(repaint: position);final Animation<double> position;final Color activeColor;14 unmodified linesfor (int i = 0; i < tickCount * progress; ++i) {final int t = (i - activeTick) % tickCount;paint.color = activeColor.withAlpha(progress < 1 ? _partiallyRevealedAlpha : _kAlphaValues[t]);canvas.drawRRect(tickFundamentalRRect, paint);canvas.rotate(_kTwoPI / tickCount);}27 unmodified lines282930313233341 unmodified line36373839404142436 unmodified lines5051525354555657585929 unmodified lines8990919293949539 unmodified lines1351361371381391401414 unmodified lines14614714814915015115215315415515615715815916014 unmodified lines17517617717817918018118218327 unmodified lines////// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/progress-indicators/>class CupertinoActivityIndicator extends StatefulWidget {/// Creates an iOS-style activity indicator that spins clockwise.const CupertinoActivityIndicator({1 unmodified linethis.color,this.animating = true,this.radius = _kDefaultIndicatorRadius,}) : assert(radius > 0.0),progress = 1.0;/// Creates a non-animated iOS-style activity indicator that displays/// a partial count of ticks based on the value of [progress].6 unmodified linesthis.color,this.radius = _kDefaultIndicatorRadius,this.progress = 1.0,}) : assert(radius > 0.0),assert(progress >= 0.0),assert(progress <= 1.0),animating = false;/// Color of the activity indicator.///29 unmodified lines@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1), vsync: this);if (widget.animating) {_controller.repeat();39 unmodified lines/// Alpha values extracted from the native component (for both dark and light mode) to/// draw the spinning ticks.const List<int> _kAlphaValues = <int>[47, 47, 47, 47, 72, 97, 122, 147];/// The alpha value that is used to draw the partially revealed ticks.const int _partiallyRevealedAlpha = 147;4 unmodified linesrequired this.activeColor,required this.radius,required this.progress,}) : tickFundamentalRRect = RRect.fromLTRBXY(-radius / _kDefaultIndicatorRadius,-radius / 3.0,radius / _kDefaultIndicatorRadius,-radius,radius / _kDefaultIndicatorRadius,radius / _kDefaultIndicatorRadius,),super(repaint: position);final Animation<double> position;final Color activeColor;14 unmodified linesfor (int i = 0; i < tickCount * progress; ++i) {final int t = (i - activeTick) % tickCount;paint.color = activeColor.withAlpha(progress < 1 ? _partiallyRevealedAlpha : _kAlphaValues[t],);canvas.drawRRect(tickFundamentalRRect, paint);canvas.rotate(_kTwoPI / tickCount);}
1 unmodified line234567101 unmodified lines10911011111211311411536 unmodified lines15215315415515615724 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032045 unmodified lines2102112122132142152162171 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart' show defaultTargetPlatform;import 'package:flutter/rendering.dart';import 'package:flutter/widgets.dart';101 unmodified linesonLookUp: onLookUp,onSearchWeb: onSearchWeb,onShare: onShare,onLiveTextInput: onLiveTextInput);/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the36 unmodified linesselectionGeometry: selectionGeometry,onCopy: onCopy,onSelectAll: onSelectAll,);/// {@macro flutter.material.AdaptiveTextSelectionToolbar.anchors}24 unmodified lines/// * [AdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the Material/// equivalent of this class and builds only the Material buttons. It/// includes a live example of using `getAdaptiveButtons`.static Iterable<Widget> getAdaptiveButtons(BuildContext context, List<ContextMenuButtonItem> buttonItems) {switch (defaultTargetPlatform) {case TargetPlatform.android:case TargetPlatform.fuchsia:case TargetPlatform.iOS:return buttonItems.map((ContextMenuButtonItem buttonItem) {return CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem,);});case TargetPlatform.linux:case TargetPlatform.windows:case TargetPlatform.macOS:return buttonItems.map((ContextMenuButtonItem buttonItem) {return CupertinoDesktopTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem,);});}}5 unmodified linesreturn const SizedBox.shrink();}final List<Widget> resultChildren = children?? getAdaptiveButtons(context, buttonItems!).toList();switch (defaultTargetPlatform) {case TargetPlatform.android:1 unmodified line2345678910101 unmodified lines11211311411511611711836 unmodified lines15515615715815916016124 unmodified lines1861871881891901911921931941951961971981992002012022032042052062075 unmodified lines2132142152162172182192201 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'package:flutter/foundation.dart' show defaultTargetPlatform;import 'package:flutter/rendering.dart';import 'package:flutter/widgets.dart';101 unmodified linesonLookUp: onLookUp,onSearchWeb: onSearchWeb,onShare: onShare,onLiveTextInput: onLiveTextInput,);/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the36 unmodified linesselectionGeometry: selectionGeometry,onCopy: onCopy,onSelectAll: onSelectAll,onShare: null, // See https://github.com/flutter/flutter/issues/141775.);/// {@macro flutter.material.AdaptiveTextSelectionToolbar.anchors}24 unmodified lines/// * [AdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the Material/// equivalent of this class and builds only the Material buttons. It/// includes a live example of using `getAdaptiveButtons`.static Iterable<Widget> getAdaptiveButtons(BuildContext context,List<ContextMenuButtonItem> buttonItems,) {switch (defaultTargetPlatform) {case TargetPlatform.android:case TargetPlatform.fuchsia:case TargetPlatform.iOS:return buttonItems.map((ContextMenuButtonItem buttonItem) {return CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem);});case TargetPlatform.linux:case TargetPlatform.windows:case TargetPlatform.macOS:return buttonItems.map((ContextMenuButtonItem buttonItem) {return CupertinoDesktopTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem);});}}5 unmodified linesreturn const SizedBox.shrink();}final List<Widget> resultChildren =children ?? getAdaptiveButtons(context, buttonItems!).toList();switch (defaultTargetPlatform) {case TargetPlatform.android:
1 unmodified line234567891011146 unmodified lines15815916016116216316413 unmodified lines17817918018118218318414 unmodified lines19920020120220320420514 unmodified lines22022122222322422522622 unmodified lines24925025125225325425539 unmodified lines29529629729829930030128 unmodified lines33033133233333433533687 unmodified lines4244254264274284294303 unmodified lines43443543643743843944044114 unmodified lines4564574584594604614621 unmodified line46446546646746846947047147247318 unmodified lines49249349449549649719 unmodified lines5175185195205215225235245255265275285295305315325335345355365375385395405415425433 unmodified lines5475485495505515525 unmodified lines55855956056156256356456556656756825 unmodified lines5945955965975985996006016026036042 unmodified lines6076086096106116126136 unmodified lines6206216226236246256266276281 unmodified line6306316321 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'button.dart';import 'colors.dart';import 'icons.dart';import 'interface_level.dart';import 'localizations.dart';146 unmodified linesthis.onNavigationNotification,List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],this.builder,this.title = '',this.onGenerateTitle,this.color,this.locale,13 unmodified lines@Deprecated('Remove this parameter as it is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.')this.useInheritedMediaQuery = false,}) : routeInformationProvider = null,14 unmodified linesthis.routerConfig,this.theme,this.builder,this.title = '',this.onGenerateTitle,this.onNavigationNotification,this.color,14 unmodified lines@Deprecated('Remove this parameter as it is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.')this.useInheritedMediaQuery = false,}) : assert(routerDelegate != null || routerConfig != null),22 unmodified lines////// When a named route is pushed with [Navigator.pushNamed], the route name is/// looked up in this map. If the name is present, the associated/// [widgets.WidgetBuilder] is used to construct a [CupertinoPageRoute] that/// performs an appropriate transition, including [Hero] animations, to the/// new route.///39 unmodified lines/// {@macro flutter.widgets.widgetsApp.title}////// This value is passed unmodified to [WidgetsApp.title].final String title;/// {@macro flutter.widgets.widgetsApp.onGenerateTitle}///28 unmodified lines////// See also:////// * <https://flutter.dev/debugging/#performance-overlay>final bool showPerformanceOverlay;/// Turns on checkerboarding of raster cache images.87 unmodified lines@Deprecated('This setting is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.')final bool useInheritedMediaQuery;3 unmodified lines/// The [HeroController] used for Cupertino page transitions.////// Used by [CupertinoTabView] and [CupertinoApp].static HeroController createCupertinoHeroController() =>HeroController(); // Linear tweening.}/// Describes how [Scrollable] widgets behave for [CupertinoApp]s.14 unmodified linesconst CupertinoScrollBehavior();@overrideWidget buildScrollbar(BuildContext context , Widget child, ScrollableDetails details) {// When modifying this function, consider modifying the implementation in// the base class as well.switch (getPlatform(context)) {1 unmodified linecase TargetPlatform.macOS:case TargetPlatform.windows:assert(details.controller != null);return CupertinoScrollbar(controller: details.controller,child: child,);case TargetPlatform.android:case TargetPlatform.fuchsia:case TargetPlatform.iOS:18 unmodified lines}return const BouncingScrollPhysics();}}class _CupertinoAppState extends State<CupertinoApp> {19 unmodified lines// _CupertinoLocalizationsDelegate.Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates {return <LocalizationsDelegate<dynamic>>[if (widget.localizationsDelegates != null)...widget.localizationsDelegates!,DefaultCupertinoLocalizations.delegate,];}Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) {return CupertinoButton.filled(padding: EdgeInsets.zero,onPressed: onPressed,child: const Icon(CupertinoIcons.search,size: 28.0,color: CupertinoColors.white,),);}WidgetsApp _buildWidgetApp(BuildContext context) {final CupertinoThemeData effectiveThemeData = CupertinoTheme.of(context);final Color color = CupertinoDynamicColor.resolve(widget.color ?? effectiveThemeData.primaryColor, context);if (_usesRouter) {return WidgetsApp.router(3 unmodified linesrouterDelegate: widget.routerDelegate,routerConfig: widget.routerConfig,backButtonDispatcher: widget.backButtonDispatcher,builder: widget.builder,title: widget.title,onGenerateTitle: widget.onGenerateTitle,5 unmodified lineslocaleListResolutionCallback: widget.localeListResolutionCallback,supportedLocales: widget.supportedLocales,showPerformanceOverlay: widget.showPerformanceOverlay,checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,showSemanticsDebugger: widget.showSemanticsDebugger,debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder,shortcuts: widget.shortcuts,actions: widget.actions,restorationScopeId: widget.restorationScopeId,25 unmodified lineslocaleListResolutionCallback: widget.localeListResolutionCallback,supportedLocales: widget.supportedLocales,showPerformanceOverlay: widget.showPerformanceOverlay,checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,showSemanticsDebugger: widget.showSemanticsDebugger,debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder,shortcuts: widget.shortcuts,actions: widget.actions,restorationScopeId: widget.restorationScopeId,2 unmodified lines@overrideWidget build(BuildContext context) {final CupertinoThemeData effectiveThemeData = (widget.theme ?? const CupertinoThemeData()).resolveFrom(context);return ScrollConfiguration(behavior: widget.scrollBehavior ?? const CupertinoScrollBehavior(),6 unmodified linescursorColor: effectiveThemeData.primaryColor,child: HeroControllerScope(controller: _heroController,child: Builder(builder: _buildWidgetApp,),),),),1 unmodified line);}}1 unmodified line23456789101112131415161718192021146 unmodified lines16816917017117217317413 unmodified lines18818919019119219319414 unmodified lines20921021121221321421514 unmodified lines23023123223323423523622 unmodified lines25926026126226326426539 unmodified lines30530630730830931031128 unmodified lines34034134234334434534687 unmodified lines4344354364374384394403 unmodified lines44444544644744844945014 unmodified lines4654664674684694704711 unmodified line47347447547647747847918 unmodified lines49849950050150250350450550650719 unmodified lines5275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855863 unmodified lines5905915925935945955965 unmodified lines60260360460560660760860961061161225 unmodified lines6386396406416426436446456466476482 unmodified lines6516526536546556566576586596606616626636646656666 unmodified lines6736746756766776786791 unmodified line6816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627631 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';/// @docImport 'package:flutter/services.dart';////// @docImport 'page_scaffold.dart';/// @docImport 'tab_view.dart';library;import 'package:flutter/gestures.dart';import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';import 'button.dart';import 'colors.dart';import 'constants.dart';import 'icons.dart';import 'interface_level.dart';import 'localizations.dart';146 unmodified linesthis.onNavigationNotification,List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],this.builder,this.title,this.onGenerateTitle,this.color,this.locale,13 unmodified lines@Deprecated('Remove this parameter as it is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.',)this.useInheritedMediaQuery = false,}) : routeInformationProvider = null,14 unmodified linesthis.routerConfig,this.theme,this.builder,this.title,this.onGenerateTitle,this.onNavigationNotification,this.color,14 unmodified lines@Deprecated('Remove this parameter as it is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.',)this.useInheritedMediaQuery = false,}) : assert(routerDelegate != null || routerConfig != null),22 unmodified lines////// When a named route is pushed with [Navigator.pushNamed], the route name is/// looked up in this map. If the name is present, the associated/// [WidgetBuilder] is used to construct a [CupertinoPageRoute] that/// performs an appropriate transition, including [Hero] animations, to the/// new route.///39 unmodified lines/// {@macro flutter.widgets.widgetsApp.title}////// This value is passed unmodified to [WidgetsApp.title].final String? title;/// {@macro flutter.widgets.widgetsApp.onGenerateTitle}///28 unmodified lines////// See also:////// * <https://flutter.dev/to/performance-overlay>final bool showPerformanceOverlay;/// Turns on checkerboarding of raster cache images.87 unmodified lines@Deprecated('This setting is now ignored. ''CupertinoApp never introduces its own MediaQuery; the View widget takes care of that. ''This feature was deprecated after v3.7.0-29.0.pre.',)final bool useInheritedMediaQuery;3 unmodified lines/// The [HeroController] used for Cupertino page transitions.////// Used by [CupertinoTabView] and [CupertinoApp].static HeroController createCupertinoHeroController() => HeroController(); // Linear tweening.}/// Describes how [Scrollable] widgets behave for [CupertinoApp]s.14 unmodified linesconst CupertinoScrollBehavior();@overrideWidget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {// When modifying this function, consider modifying the implementation in// the base class as well.switch (getPlatform(context)) {1 unmodified linecase TargetPlatform.macOS:case TargetPlatform.windows:assert(details.controller != null);return CupertinoScrollbar(controller: details.controller, child: child);case TargetPlatform.android:case TargetPlatform.fuchsia:case TargetPlatform.iOS:18 unmodified lines}return const BouncingScrollPhysics();}@overrideMultitouchDragStrategy getMultitouchDragStrategy(BuildContext context) =>MultitouchDragStrategy.averageBoundaryPointers;}class _CupertinoAppState extends State<CupertinoApp> {19 unmodified lines// _CupertinoLocalizationsDelegate.Iterable<LocalizationsDelegate<dynamic>> get _localizationsDelegates {return <LocalizationsDelegate<dynamic>>[if (widget.localizationsDelegates != null) ...widget.localizationsDelegates!,DefaultCupertinoLocalizations.delegate,];}Widget _exitWidgetSelectionButtonBuilder(BuildContext context, {required VoidCallback onPressed,required String semanticLabel,required GlobalKey key,}) {return _CupertinoInspectorButton.filled(onPressed: onPressed,semanticLabel: semanticLabel,icon: CupertinoIcons.xmark,buttonKey: key,);}Widget _moveExitWidgetSelectionButtonBuilder(BuildContext context, {required VoidCallback onPressed,required String semanticLabel,bool isLeftAligned = true,}) {return _CupertinoInspectorButton.iconOnly(onPressed: onPressed,semanticLabel: semanticLabel,icon: isLeftAligned ? CupertinoIcons.arrow_right : CupertinoIcons.arrow_left,);}Widget _tapBehaviorButtonBuilder(BuildContext context, {required VoidCallback onPressed,required String semanticLabel,required bool selectionOnTapEnabled,}) {return _CupertinoInspectorButton.toggle(onPressed: onPressed,semanticLabel: semanticLabel,// This unicode icon is also used for the Material-styled button and for// DevTools. It should be updated in all 3 places if changed.icon: const IconData(0x1F74A),toggledOn: selectionOnTapEnabled,);}WidgetsApp _buildWidgetApp(BuildContext context) {final CupertinoThemeData effectiveThemeData = CupertinoTheme.of(context);final Color color = CupertinoDynamicColor.resolve(widget.color ?? effectiveThemeData.primaryColor,context,);if (_usesRouter) {return WidgetsApp.router(3 unmodified linesrouterDelegate: widget.routerDelegate,routerConfig: widget.routerConfig,backButtonDispatcher: widget.backButtonDispatcher,onNavigationNotification: widget.onNavigationNotification,builder: widget.builder,title: widget.title,onGenerateTitle: widget.onGenerateTitle,5 unmodified lineslocaleListResolutionCallback: widget.localeListResolutionCallback,supportedLocales: widget.supportedLocales,showPerformanceOverlay: widget.showPerformanceOverlay,showSemanticsDebugger: widget.showSemanticsDebugger,debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder,moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder,tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder,shortcuts: widget.shortcuts,actions: widget.actions,restorationScopeId: widget.restorationScopeId,25 unmodified lineslocaleListResolutionCallback: widget.localeListResolutionCallback,supportedLocales: widget.supportedLocales,showPerformanceOverlay: widget.showPerformanceOverlay,showSemanticsDebugger: widget.showSemanticsDebugger,debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder,moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder,tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder,shortcuts: widget.shortcuts,actions: widget.actions,restorationScopeId: widget.restorationScopeId,2 unmodified lines@overrideWidget build(BuildContext context) {final CupertinoThemeData effectiveThemeData = (widget.theme ?? const CupertinoThemeData()).resolveFrom(context);// Prefer theme brightness if set, otherwise check system brightness.final Brightness brightness =effectiveThemeData.brightness ?? MediaQuery.platformBrightnessOf(context);SystemChrome.setSystemUIOverlayStyle(brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark,);return ScrollConfiguration(behavior: widget.scrollBehavior ?? const CupertinoScrollBehavior(),6 unmodified linescursorColor: effectiveThemeData.primaryColor,child: HeroControllerScope(controller: _heroController,child: Builder(builder: _buildWidgetApp),),),),1 unmodified line);}}class _CupertinoInspectorButton extends InspectorButton {const _CupertinoInspectorButton.filled({required super.onPressed,required super.semanticLabel,required super.icon,super.buttonKey,}) : super.filled();const _CupertinoInspectorButton.toggle({required super.onPressed,required super.semanticLabel,required super.icon,super.toggledOn,}) : super.toggle();const _CupertinoInspectorButton.iconOnly({required super.onPressed,required super.semanticLabel,required super.icon,}) : super.iconOnly();@overrideWidget build(BuildContext context) {final Icon buttonIcon = Icon(icon,semanticLabel: semanticLabel,size: iconSizeForVariant,color: foregroundColor(context),);return Padding(key: buttonKey,padding: const EdgeInsets.all((kMinInteractiveDimensionCupertino - InspectorButton.buttonSize) / 2,),child:variant == InspectorButtonVariant.toggle && !toggledOn!? CupertinoButton.tinted(minSize: InspectorButton.buttonSize,onPressed: onPressed,padding: EdgeInsets.zero,child: buttonIcon,): CupertinoButton(minSize: InspectorButton.buttonSize,onPressed: onPressed,padding: EdgeInsets.zero,color: backgroundColor(context),child: buttonIcon,),);}@overrideColor foregroundColor(BuildContext context) {final Color primaryColor = CupertinoTheme.of(context).primaryColor;final Color secondaryColor = CupertinoTheme.of(context).primaryContrastingColor;switch (variant) {case InspectorButtonVariant.filled:return secondaryColor;case InspectorButtonVariant.iconOnly:return primaryColor;case InspectorButtonVariant.toggle:return !toggledOn! ? primaryColor : secondaryColor;}}@overrideColor backgroundColor(BuildContext context) {final Color primaryColor = CupertinoTheme.of(context).primaryColor;switch (variant) {case InspectorButtonVariant.filled:case InspectorButtonVariant.toggle:return primaryColor;case InspectorButtonVariant.iconOnly:return const Color(0x00000000);}}}
1 unmodified line23456763 unmodified lines7172737475767778798072 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218314 unmodified lines19819920020120220320420520620715 unmodified lines22322422522622722822923023123223323423523623716 unmodified lines2542552562572582592602612622632642652662672684 unmodified lines2732742752762772782792802812821 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:ui' show ImageFilter;import 'package:flutter/foundation.dart';63 unmodified lineswidth: 0.0, // 0.0 means one physical pixel),),}) : assert(items.length >= 2,"Tabs need at least 2 items to conform to Apple's HIG",),assert(0 <= currentIndex && currentIndex < items.length),assert(height >= 0.0);72 unmodified linesBorderSide resolveBorderSide(BorderSide side) {return side == BorderSide.none? side: side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context));}// Return the border as is when it's a subclass.final Border? resolvedBorder = border == null || border.runtimeType != Border? border: Border(top: resolveBorderSide(border!.top),left: resolveBorderSide(border!.left),bottom: resolveBorderSide(border!.bottom),right: resolveBorderSide(border!.right),);final Color inactive = CupertinoDynamicColor.resolve(inactiveColor, context);Widget result = DecoratedBox(decoration: BoxDecoration(border: resolvedBorder,color: backgroundColor,),child: SizedBox(height: height + bottomPadding,child: IconTheme.merge( // Default with the inactive state.data: IconThemeData(color: inactive, size: iconSize),child: DefaultTextStyle( // Default with the inactive state.style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(color: inactive),child: Padding(padding: EdgeInsets.only(bottom: bottomPadding),14 unmodified linesif (!opaque(context)) {// For non-opaque backgrounds, apply a blur effect.result = ClipRect(child: BackdropFilter(filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),child: result,),);}15 unmodified lineschild: TextFieldTapRegion(child: Semantics(selected: active,hint: localizations.tabSemanticsLabel(tabIndex: index + 1,tabCount: items.length,),child: MouseRegion(cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,child: GestureDetector(behavior: HitTestBehavior.opaque,onTap: onTap == null ? null : () { onTap!(index); },child: Padding(padding: const EdgeInsets.only(bottom: 4.0),child: Column(16 unmodified linesList<Widget> _buildSingleTabItem(BottomNavigationBarItem item, bool active) {return <Widget>[Expanded(child: Center(child: active ? item.activeIcon : item.icon),),if (item.label != null) Text(item.label!),];}/// Change the active tab item's icon and title colors to active.Widget _wrapActiveItem(BuildContext context, Widget item, { required bool active }) {if (!active) {return item;}4 unmodified lines);return IconTheme.merge(data: IconThemeData(color: activeColor),child: DefaultTextStyle.merge(style: TextStyle(color: activeColor),child: item,),);}1 unmodified line23456789101163 unmodified lines7576777879808172 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318414 unmodified lines19920020120220320420515 unmodified lines22122222322422522622722822923023123223323423523623716 unmodified lines2542552562572582592602612622632642652664 unmodified lines2712722732742752762771 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'tab_scaffold.dart';/// @docImport 'tab_view.dart';library;import 'dart:ui' show ImageFilter;import 'package:flutter/foundation.dart';63 unmodified lineswidth: 0.0, // 0.0 means one physical pixel),),}) : assert(items.length >= 2, "Tabs need at least 2 items to conform to Apple's HIG"),assert(0 <= currentIndex && currentIndex < items.length),assert(height >= 0.0);72 unmodified linesBorderSide resolveBorderSide(BorderSide side) {return side == BorderSide.none? side: side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context));}// Return the border as is when it's a subclass.final Border? resolvedBorder =border == null || border.runtimeType != Border? border: Border(top: resolveBorderSide(border!.top),left: resolveBorderSide(border!.left),bottom: resolveBorderSide(border!.bottom),right: resolveBorderSide(border!.right),);final Color inactive = CupertinoDynamicColor.resolve(inactiveColor, context);Widget result = DecoratedBox(decoration: BoxDecoration(border: resolvedBorder, color: backgroundColor),child: SizedBox(height: height + bottomPadding,child: IconTheme.merge(// Default with the inactive state.data: IconThemeData(color: inactive, size: iconSize),child: DefaultTextStyle(// Default with the inactive state.style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(color: inactive),child: Padding(padding: EdgeInsets.only(bottom: bottomPadding),14 unmodified linesif (!opaque(context)) {// For non-opaque backgrounds, apply a blur effect.result = ClipRect(child: BackdropFilter(filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: result),);}15 unmodified lineschild: TextFieldTapRegion(child: Semantics(selected: active,hint: localizations.tabSemanticsLabel(tabIndex: index + 1, tabCount: items.length),child: MouseRegion(cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,child: GestureDetector(behavior: HitTestBehavior.opaque,onTap:onTap == null? null: () {onTap!(index);},child: Padding(padding: const EdgeInsets.only(bottom: 4.0),child: Column(16 unmodified linesList<Widget> _buildSingleTabItem(BottomNavigationBarItem item, bool active) {return <Widget>[Expanded(child: Center(child: active ? item.activeIcon : item.icon)),if (item.label != null) Text(item.label!),];}/// Change the active tab item's icon and title colors to active.Widget _wrapActiveItem(BuildContext context, Widget item, {required bool active}) {if (!active) {return item;}4 unmodified lines);return IconTheme.merge(data: IconThemeData(color: activeColor),child: DefaultTextStyle.merge(style: TextStyle(color: activeColor), child: item),);}
1 unmodified line2345678910111213141516171819205 unmodified lines2627282930313 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757623 unmodified lines1001011021031041051061071081091101111121131143 unmodified lines1181191201211221231241251264 unmodified lines13113213313413513613713813914014114 unmodified lines15615715815916016116216316416516616716816917017117214 unmodified lines1871881891901911921931941 unmodified line1961971981992002012022032042052062072082092102112122132142152162172182192202212221 unmodified line2242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842851 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'constants.dart';import 'theme.dart';// Measured against iOS 12 in Xcode.const EdgeInsets _kButtonPadding = EdgeInsets.all(16.0);const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric(vertical: 14.0,horizontal: 64.0,);/// An iOS-style button.///5 unmodified lines/// [EdgeInsets.zero], should be used to prevent clipping larger [child]/// widgets.////// {@tool dartpad}/// This sample shows produces an enabled and disabled [CupertinoButton] and/// [CupertinoButton.filled].3 unmodified lines////// See also:////// * <https://developer.apple.com/ios/human-interface-guidelines/controls/buttons/>class CupertinoButton extends StatefulWidget {/// Creates an iOS-style button.const CupertinoButton({super.key,required this.child,this.padding,this.color,this.disabledColor = CupertinoColors.quaternarySystemFill,this.minSize = kMinInteractiveDimensionCupertino,this.pressedOpacity = 0.4,this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),this.alignment = Alignment.center,required this.onPressed,}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),_filled = false;/// Creates an iOS-style button with a filled background.////// The background color is derived from the [CupertinoTheme]'s `primaryColor`.////// To specify a custom background color, use the [color] argument of the/// default constructor.const CupertinoButton.filled({super.key,required this.child,this.padding,this.disabledColor = CupertinoColors.quaternarySystemFill,this.minSize = kMinInteractiveDimensionCupertino,this.pressedOpacity = 0.4,this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),this.alignment = Alignment.center,required this.onPressed,}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),color = null,_filled = true;/// The widget below this widget in the tree.///23 unmodified lines/// The callback that is called when the button is tapped or otherwise activated.////// If this is set to null, the button will be disabled.final VoidCallback? onPressed;/// Minimum size of the button.////// Defaults to kMinInteractiveDimensionCupertino which the iOS Human/// Interface Guidelines recommends as the minimum tappable area.final double? minSize;/// The opacity that the button will fade to when it is pressed./// The button will have an opacity of 1.0 when it is not pressed.///3 unmodified lines/// The radius of the button's corners when it has a background color.////// Defaults to round corners of 8 logical pixels.final BorderRadius? borderRadius;/// The alignment of the button's [child].////// Typically buttons are sized to be just big enough to contain the child and its4 unmodified lines/// Always defaults to [Alignment.center].final AlignmentGeometry alignment;final bool _filled;/// Whether the button is enabled or disabled. Buttons are disabled by default. To/// enable a button, set its [onPressed] property to a non-null value.bool get enabled => onPressed != null;@overrideState<CupertinoButton> createState() => _CupertinoButtonState();14 unmodified lineslate AnimationController _animationController;late Animation<double> _opacityAnimation;@overridevoid initState() {super.initState();_animationController = AnimationController(duration: const Duration(milliseconds: 200),value: 0.0,vsync: this,);_opacityAnimation = _animationController.drive(CurveTween(curve: Curves.decelerate)).drive(_opacityTween);_setTween();}14 unmodified lines}bool _buttonHeldDown = false;void _handleTapDown(TapDownDetails event) {if (!_buttonHeldDown) {_buttonHeldDown = true;_animate();1 unmodified line}void _handleTapUp(TapUpDetails event) {if (_buttonHeldDown) {_buttonHeldDown = false;_animate();}}void _handleTapCancel() {if (_buttonHeldDown) {_buttonHeldDown = false;_animate();}}void _animate() {if (_animationController.isAnimating) {return;}final bool wasHeldDown = _buttonHeldDown;final TickerFuture ticker = _buttonHeldDown? _animationController.animateTo(1.0, duration: kFadeOutDuration, curve: Curves.easeInOutCubicEmphasized): _animationController.animateTo(0.0, duration: kFadeInDuration, curve: Curves.easeOutCubic);ticker.then<void>((void value) {if (mounted && wasHeldDown != _buttonHeldDown) {_animate();1 unmodified line});}@overrideWidget build(BuildContext context) {final bool enabled = widget.enabled;final CupertinoThemeData themeData = CupertinoTheme.of(context);final Color primaryColor = themeData.primaryColor;final Color? backgroundColor = widget.color == null? (widget._filled ? primaryColor : null): CupertinoDynamicColor.maybeResolve(widget.color, context);final Color foregroundColor = backgroundColor != null? themeData.primaryContrastingColor: enabled? primaryColor: CupertinoDynamicColor.resolve(CupertinoColors.placeholderText, context);final TextStyle textStyle = themeData.textTheme.textStyle.copyWith(color: foregroundColor);return MouseRegion(cursor: enabled && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,child: GestureDetector(behavior: HitTestBehavior.opaque,onTapDown: enabled ? _handleTapDown : null,onTapUp: enabled ? _handleTapUp : null,onTapCancel: enabled ? _handleTapCancel : null,onTap: widget.onPressed,child: Semantics(button: true,child: ConstrainedBox(constraints: widget.minSize == null? const BoxConstraints(): BoxConstraints(minWidth: widget.minSize!,minHeight: widget.minSize!,),child: FadeTransition(opacity: _opacityAnimation,child: DecoratedBox(decoration: BoxDecoration(borderRadius: widget.borderRadius,color: backgroundColor != null && !enabled? CupertinoDynamicColor.resolve(widget.disabledColor, context): backgroundColor,),child: Padding(padding: widget.padding ?? (backgroundColor != null? _kBackgroundButtonPadding: _kButtonPadding),child: Align(alignment: widget.alignment,widthFactor: 1.0,heightFactor: 1.0,child: DefaultTextStyle(style: textStyle,child: IconTheme(data: IconThemeData(color: foregroundColor),child: widget.child,),),),1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647485 unmodified lines545556575859606162633 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616723 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182193 unmodified lines2232242252262272282292302312322332342352364 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930014 unmodified lines31531631731831932032132232332432532632732832933033133233333433533633733833934034114 unmodified lines3563573583593603613623633643651 unmodified line3673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274281 unmodified line4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775781 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'nav_bar.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/semantics.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'constants.dart';import 'text_theme.dart';import 'theme.dart';// Measured against iOS (17) [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS)./// The size of a [CupertinoButton]./// Based on the iOS (17) [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS).enum CupertinoButtonSize {/// Displays a smaller button with round sides and smaller text (uses [CupertinoTextThemeData.actionSmallTextStyle]).small,/// Displays a medium sized button with round sides and regular-sized text.medium,/// Displays a (classic) large button with rounded edges and regular-sized text.large,}/// The style of a [CupertinoButton] that changes the style of the button's background.////// Based on the iOS Human Interface Guidelines (https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS).enum _CupertinoButtonStyle {/// No background or border, primary foreground color.plain,/// Translucent background, primary foreground color.tinted,/// Solid background, contrasting foreground color.filled,}/// An iOS-style button.///5 unmodified lines/// [EdgeInsets.zero], should be used to prevent clipping larger [child]/// widgets.////// Preserves any parent [IconThemeData] but overwrites its [IconThemeData.color]/// with the [CupertinoThemeData.primaryColor] (or/// [CupertinoThemeData.primaryContrastingColor] if the button is disabled).////// {@tool dartpad}/// This sample shows produces an enabled and disabled [CupertinoButton] and/// [CupertinoButton.filled].3 unmodified lines////// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/buttons/>class CupertinoButton extends StatefulWidget {/// Creates an iOS-style button.const CupertinoButton({super.key,required this.child,this.sizeStyle = CupertinoButtonSize.large,this.padding,this.color,this.disabledColor = CupertinoColors.quaternarySystemFill,@Deprecated('Use minimumSize instead. ''This feature was deprecated after v3.28.0-3.0.pre.',)this.minSize,this.minimumSize,this.pressedOpacity = 0.4,this.borderRadius,this.alignment = Alignment.center,this.focusColor,this.focusNode,this.onFocusChange,this.autofocus = false,this.mouseCursor,this.onLongPress,required this.onPressed,}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),assert(minimumSize == null || minSize == null),_style = _CupertinoButtonStyle.plain;/// Creates an iOS-style button with a tinted background.////// The background color is derived from the [CupertinoTheme]'s `primaryColor` + transparency./// The foreground color is the [CupertinoTheme]'s `primaryColor`.////// To specify a custom background color, use the [color] argument of the/// default constructor.////// To match the iOS "grey" button style, set [color] to [CupertinoColors.systemGrey].const CupertinoButton.tinted({super.key,required this.child,this.sizeStyle = CupertinoButtonSize.large,this.padding,this.color,this.disabledColor = CupertinoColors.tertiarySystemFill,@Deprecated('Use minimumSize instead. ''This feature was deprecated after v3.28.0-3.0.pre.',)this.minSize,this.minimumSize,this.pressedOpacity = 0.4,this.borderRadius,this.alignment = Alignment.center,this.focusColor,this.focusNode,this.onFocusChange,this.autofocus = false,this.mouseCursor,this.onLongPress,required this.onPressed,}) : assert(minimumSize == null || minSize == null),_style = _CupertinoButtonStyle.tinted;/// Creates an iOS-style button with a filled background.////// The background color is derived from the [color] argument./// The foreground color is the [CupertinoTheme]'s `primaryContrastingColor`.const CupertinoButton.filled({super.key,required this.child,this.sizeStyle = CupertinoButtonSize.large,this.padding,this.color,this.disabledColor = CupertinoColors.tertiarySystemFill,@Deprecated('Use minimumSize instead. ''This feature was deprecated after v3.28.0-3.0.pre.',)this.minSize,this.minimumSize,this.pressedOpacity = 0.4,this.borderRadius,this.alignment = Alignment.center,this.focusColor,this.focusNode,this.onFocusChange,this.autofocus = false,this.mouseCursor,this.onLongPress,required this.onPressed,}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),assert(minimumSize == null || minSize == null),_style = _CupertinoButtonStyle.filled;/// The widget below this widget in the tree.///23 unmodified lines/// The callback that is called when the button is tapped or otherwise activated.////// If [onPressed] and [onLongPress] callbacks are null, then the button will be disabled.final VoidCallback? onPressed;/// If [onPressed] and [onLongPress] callbacks are null, then the button will be disabled.final VoidCallback? onLongPress;/// Minimum size of the button.////// Defaults to kMinInteractiveDimensionCupertino which the iOS Human/// Interface Guidelines recommends as the minimum tappable area.@Deprecated('Use minimumSize instead. ''This feature was deprecated after v3.28.0-3.0.pre.',)final double? minSize;/// The minimum size of the button.////// Defaults to a button with a height and a width of/// [kMinInteractiveDimensionCupertino], which the iOS Human/// Interface Guidelines recommends as the minimum tappable area.final Size? minimumSize;/// The opacity that the button will fade to when it is pressed./// The button will have an opacity of 1.0 when it is not pressed.///3 unmodified lines/// The radius of the button's corners when it has a background color.////// Defaults to [kCupertinoButtonSizeBorderRadius], based on [sizeStyle].final BorderRadius? borderRadius;/// The size of the button.////// Defaults to [CupertinoButtonSize.large].final CupertinoButtonSize sizeStyle;/// The alignment of the button's [child].////// Typically buttons are sized to be just big enough to contain the child and its4 unmodified lines/// Always defaults to [Alignment.center].final AlignmentGeometry alignment;/// The color to use for the focus highlight for keyboard interactions.////// Defaults to a slightly transparent [color]. If [color] is null, defaults/// to a slightly transparent [CupertinoColors.activeBlue]. Slightly/// transparent in this context means the color is used with an opacity of/// 0.80, a brightness of 0.69 and a saturation of 0.835.final Color? focusColor;/// {@macro flutter.widgets.Focus.focusNode}final FocusNode? focusNode;/// Handler called when the focus changes.////// Called with true if this widget's node gains focus, and false if it loses/// focus.final ValueChanged<bool>? onFocusChange;/// {@macro flutter.widgets.Focus.autofocus}final bool autofocus;/// The cursor for a mouse pointer when it enters or is hovering over the widget.////// If [mouseCursor] is a [WidgetStateMouseCursor],/// [WidgetStateProperty.resolve] is used for the following [WidgetState]:/// * [WidgetState.disabled].////// If null, then [MouseCursor.defer] is used when the button is disabled./// When the button is enabled, [SystemMouseCursors.click] is used on Web/// and [MouseCursor.defer] is used on other platforms.////// See also:////// * [WidgetStateMouseCursor], a [MouseCursor] that implements/// [WidgetStateProperty] which is used in APIs that need to accept/// either a [MouseCursor] or a [WidgetStateProperty].final MouseCursor? mouseCursor;final _CupertinoButtonStyle _style;/// Whether the button is enabled or disabled. Buttons are disabled by default. To/// enable a button, set [onPressed] or [onLongPress] to a non-null value.bool get enabled => onPressed != null || onLongPress != null;/// The distance a button needs to be moved after being pressed for its opacity to change.////// The opacity changes when the position moved is this distance away from the button.static double tapMoveSlop() {return switch (defaultTargetPlatform) {TargetPlatform.iOS ||TargetPlatform.android ||TargetPlatform.fuchsia => kCupertinoButtonTapMoveSlop,TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 0.0,};}@overrideState<CupertinoButton> createState() => _CupertinoButtonState();14 unmodified lineslate AnimationController _animationController;late Animation<double> _opacityAnimation;late bool isFocused;static final WidgetStateProperty<MouseCursor> _defaultCursor =WidgetStateProperty.resolveWith<MouseCursor>((Set<WidgetState> states) {return !states.contains(WidgetState.disabled) && kIsWeb? SystemMouseCursors.click: MouseCursor.defer;});@overridevoid initState() {super.initState();isFocused = false;_animationController = AnimationController(duration: const Duration(milliseconds: 200),value: 0.0,vsync: this,);_opacityAnimation = _animationController.drive(CurveTween(curve: Curves.decelerate)).drive(_opacityTween);_setTween();}14 unmodified lines}bool _buttonHeldDown = false;bool _tapInProgress = false;void _handleTapDown(TapDownDetails event) {_tapInProgress = true;if (!_buttonHeldDown) {_buttonHeldDown = true;_animate();1 unmodified line}void _handleTapUp(TapUpDetails event) {_tapInProgress = false;if (_buttonHeldDown) {_buttonHeldDown = false;_animate();}final RenderBox renderObject = context.findRenderObject()! as RenderBox;final Offset localPosition = renderObject.globalToLocal(event.globalPosition);if (renderObject.paintBounds.inflate(CupertinoButton.tapMoveSlop()).contains(localPosition)) {_handleTap();}}void _handleTapCancel() {_tapInProgress = false;if (_buttonHeldDown) {_buttonHeldDown = false;_animate();}}void _handleTapMove(TapMoveDetails event) {final RenderBox renderObject = context.findRenderObject()! as RenderBox;final Offset localPosition = renderObject.globalToLocal(event.globalPosition);final bool buttonShouldHeldDown = renderObject.paintBounds.inflate(CupertinoButton.tapMoveSlop()).contains(localPosition);if (_tapInProgress && buttonShouldHeldDown != _buttonHeldDown) {_buttonHeldDown = buttonShouldHeldDown;_animate();}}void _handleTap([Intent? _]) {if (widget.onPressed != null) {widget.onPressed!();context.findRenderObject()!.sendSemanticsEvent(const TapSemanticEvent());}}void _animate() {if (_animationController.isAnimating) {return;}final bool wasHeldDown = _buttonHeldDown;final TickerFuture ticker =_buttonHeldDown? _animationController.animateTo(1.0,duration: kFadeOutDuration,curve: Curves.easeInOutCubicEmphasized,): _animationController.animateTo(0.0,duration: kFadeInDuration,curve: Curves.easeOutCubic,);ticker.then<void>((void value) {if (mounted && wasHeldDown != _buttonHeldDown) {_animate();1 unmodified line});}void _onShowFocusHighlight(bool showHighlight) {setState(() {isFocused = showHighlight;});}late final Map<Type, Action<Intent>> _actionMap = <Type, Action<Intent>>{ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: _handleTap),};@overrideWidget build(BuildContext context) {final bool enabled = widget.enabled;final Size? minimumSize =widget.minimumSize == null? widget.minSize == null? null: Size(widget.minSize!, widget.minSize!): widget.minimumSize!;final CupertinoThemeData themeData = CupertinoTheme.of(context);final Color primaryColor = themeData.primaryColor;final Color? backgroundColor = (widget.color == null? widget._style != _CupertinoButtonStyle.plain? primaryColor: null: CupertinoDynamicColor.maybeResolve(widget.color, context))?.withOpacity(widget._style == _CupertinoButtonStyle.tinted? CupertinoTheme.brightnessOf(context) == Brightness.light? kCupertinoButtonTintedOpacityLight: kCupertinoButtonTintedOpacityDark: widget.color?.opacity ?? 1.0,);final Color foregroundColor =widget._style == _CupertinoButtonStyle.filled? themeData.primaryContrastingColor: enabled? primaryColor: CupertinoDynamicColor.resolve(CupertinoColors.tertiaryLabel, context);final Color effectiveFocusOutlineColor =widget.focusColor ??HSLColor.fromColor((backgroundColor ?? CupertinoColors.activeBlue).withOpacity(kCupertinoFocusColorOpacity,),).withLightness(kCupertinoFocusColorBrightness).withSaturation(kCupertinoFocusColorSaturation).toColor();final TextStyle textStyle = (widget.sizeStyle == CupertinoButtonSize.small? themeData.textTheme.actionSmallTextStyle: themeData.textTheme.actionTextStyle).copyWith(color: foregroundColor);final IconThemeData iconTheme = IconTheme.of(context).copyWith(color: foregroundColor,size:textStyle.fontSize != null ? textStyle.fontSize! * 1.2 : kCupertinoButtonDefaultIconSize,);final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context);final Set<WidgetState> states = <WidgetState>{if (!enabled) WidgetState.disabled};final MouseCursor effectiveMouseCursor =WidgetStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states) ??_defaultCursor.resolve(states);return MouseRegion(cursor: effectiveMouseCursor,child: FocusableActionDetector(actions: _actionMap,focusNode: widget.focusNode,autofocus: widget.autofocus,onFocusChange: widget.onFocusChange,onShowFocusHighlight: _onShowFocusHighlight,enabled: enabled,child: RawGestureDetector(behavior: HitTestBehavior.opaque,gestures: <Type, GestureRecognizerFactory>{TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(() => TapGestureRecognizer(postAcceptSlopTolerance: null),(TapGestureRecognizer instance) {instance.onTapDown = enabled ? _handleTapDown : null;instance.onTapUp = enabled ? _handleTapUp : null;instance.onTapCancel = enabled ? _handleTapCancel : null;instance.onTapMove = enabled ? _handleTapMove : null;instance.gestureSettings = gestureSettings;},),if (widget.onLongPress != null)LongPressGestureRecognizer:GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(() => LongPressGestureRecognizer(),(LongPressGestureRecognizer instance) {instance.onLongPress = widget.onLongPress;instance.gestureSettings = gestureSettings;},),},child: Semantics(button: true,child: ConstrainedBox(constraints: BoxConstraints(minWidth:minimumSize?.width ??kCupertinoButtonMinSize[widget.sizeStyle] ??kMinInteractiveDimensionCupertino,minHeight:minimumSize?.height ??kCupertinoButtonMinSize[widget.sizeStyle] ??kMinInteractiveDimensionCupertino,),child: FadeTransition(opacity: _opacityAnimation,child: DecoratedBox(decoration: BoxDecoration(border:enabled && isFocused? Border.fromBorderSide(BorderSide(color: effectiveFocusOutlineColor,width: 3.5,strokeAlign: BorderSide.strokeAlignOutside,),): null,borderRadius:widget.borderRadius ?? kCupertinoButtonSizeBorderRadius[widget.sizeStyle],color:backgroundColor != null && !enabled? CupertinoDynamicColor.resolve(widget.disabledColor, context): backgroundColor,),child: Padding(padding: widget.padding ?? kCupertinoButtonPadding[widget.sizeStyle]!,child: Align(alignment: widget.alignment,widthFactor: 1.0,heightFactor: 1.0,child: DefaultTextStyle(style: textStyle,child: IconTheme(data: iconTheme, child: widget.child),),),),
1 unmodified line234567891011121314151617181920212223242510 unmodified lines36373839404120 unmodified lines626364656667686970717273747533 unmodified lines10911011111211311411511611711811912012112212312412512612722 unmodified lines1501511521531541551561572 unmodified lines16016116216316416516616716816917017117217328 unmodified lines20220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225340 unmodified lines2942952962972982993003013021 unmodified line30430530630730830911 unmodified lines3213223233243253263273283293303313326 unmodified lines33934034134234334434534634734834935011 unmodified lines3623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933941 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'colors.dart';import 'constants.dart';import 'toggleable.dart';// Examples can assume:// bool _throwShotAway = false;// late StateSetter setState;// The relative values needed to transform a color to it's equivalent focus// outline color.const double _kCupertinoFocusColorOpacity = 0.80;const double _kCupertinoFocusColorBrightness = 0.69;const double _kCupertinoFocusColorSaturation = 0.835;/// A macOS style checkbox.////// The checkbox itself does not maintain any state. Instead, when the state of/// the checkbox changes, the widget calls the [onChanged] callback. Most/// widgets that use a checkbox will listen for the [onChanged] callback and10 unmodified lines/// ([CupertinoSwitch] in Flutter) instead, or to find a creative custom/// solution.////// See also:////// * [Checkbox], the Material Design equivalent.20 unmodified linesrequired this.value,this.tristate = false,required this.onChanged,this.activeColor,this.inactiveColor,this.checkColor,this.focusColor,this.focusNode,this.autofocus = false,this.side,this.shape,}) : assert(tristate || value != null);/// Whether this checkbox is checked.33 unmodified lines/// ```final ValueChanged<bool?>? onChanged;/// The color to use when this checkbox is checked.////// Defaults to [CupertinoColors.activeBlue].final Color? activeColor;/// The color used if the checkbox is inactive.////// By default, [CupertinoColors.inactiveGray] is used.final Color? inactiveColor;/// The color to use for the check icon when this checkbox is checked.////// If null, then the value of [CupertinoColors.white] is used.final Color? checkColor;/// If true, the checkbox's [value] can be true, false, or null.22 unmodified lines/// The color and width of the checkbox's border.////// If this property is null, then the side defaults to a one pixel wide/// black, solid border.final BorderSide? side;/// The shape of the checkbox.2 unmodified lines/// [RoundedRectangleBorder] with a circular corner radius of 4.0.final OutlinedBorder? shape;/// The width of a checkbox widget.static const double width = 18.0;@overrideState<CupertinoCheckbox> createState() => _CupertinoCheckboxState();}class _CupertinoCheckboxState extends State<CupertinoCheckbox> with TickerProviderStateMixin, ToggleableStateMixin {final _CheckboxPainter _painter = _CheckboxPainter();bool? _previousValue;28 unmodified lines@overridebool? get value => widget.value;void onFocusChange(bool value) {if (focused != value) {focused = value;}}@overrideWidget build(BuildContext context) {final Color effectiveActiveColor = widget.activeColor?? CupertinoColors.activeBlue;final Color? inactiveColor = widget.inactiveColor;final Color effectiveInactiveColor = inactiveColor?? CupertinoColors.inactiveGray;final Color effectiveFocusOverlayColor = widget.focusColor?? HSLColor.fromColor(effectiveActiveColor.withOpacity(_kCupertinoFocusColorOpacity)).withLightness(_kCupertinoFocusColorBrightness).withSaturation(_kCupertinoFocusColorSaturation).toColor();final Color effectiveCheckColor = widget.checkColor?? CupertinoColors.white;return Semantics(checked: widget.value ?? false,mixed: widget.tristate ? widget.value == null : null,child: buildToggleable(focusNode: widget.focusNode,autofocus: widget.autofocus,onFocusChange: onFocusChange,size: const Size.square(kMinInteractiveDimensionCupertino),painter: _painter..focusColor = effectiveFocusOverlayColor..isFocused = focused..downPosition = downPosition..activeColor = effectiveActiveColor..inactiveColor = effectiveInactiveColor..checkColor = effectiveCheckColor..value = value..previousValue = _previousValue..isActive = widget.onChanged != null..shape = widget.shape ?? RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0),)..side = widget.side,),);}40 unmodified linesnotifyListeners();}BorderSide? get side => _side;BorderSide? _side;set side(BorderSide? value) {if (_side == value) {return;}1 unmodified linenotifyListeners();}Rect _outerRectAt(Offset origin) {const double size = CupertinoCheckbox.width;final Rect rect = Rect.fromLTWH(origin.dx, origin.dy, size, size);11 unmodified linesreturn Paint()..color = checkColor..style = PaintingStyle.stroke..strokeWidth = 2.5..strokeCap = StrokeCap.round;}void _drawBox(Canvas canvas, Rect outer, Paint paint, BorderSide? side, bool fill) {if (fill) {canvas.drawPath(shape.getOuterPath(outer), paint);}if (side != null) {6 unmodified lines// The ratios for the offsets below were found from looking at the checkbox// examples on in the HIG docs. The distance from the needed point to the// edge was measured, then divided by the total width.const Offset start = Offset(CupertinoCheckbox.width * 0.25, CupertinoCheckbox.width * 0.52);const Offset mid = Offset(CupertinoCheckbox.width * 0.46, CupertinoCheckbox.width * 0.75);const Offset end = Offset(CupertinoCheckbox.width * 0.72, CupertinoCheckbox.width * 0.29);path.moveTo(origin.dx + start.dx, origin.dy + start.dy);path.lineTo(origin.dx + mid.dx, origin.dy + mid.dy);canvas.drawPath(path, paint);path.moveTo(origin.dx + mid.dx, origin.dy + mid.dy);path.lineTo(origin.dx + end.dx, origin.dy + end.dy);canvas.drawPath(path, paint);11 unmodified linesvoid paint(Canvas canvas, Size size) {final Paint strokePaint = _createStrokePaint();final Offset origin = size / 2.0 - const Size.square(CupertinoCheckbox.width) / 2.0 as Offset;final Rect outer = _outerRectAt(origin);final Paint paint = Paint()..color = _colorAt(value ?? true);if (value == false) {final BorderSide border = side ?? BorderSide(color: paint.color);_drawBox(canvas, outer, paint, border, false);} else {_drawBox(canvas, outer, paint, side, true);if (value ?? false) {_drawCheck(canvas, origin, strokePaint);} else {_drawDash(canvas, origin, strokePaint);}}if (isFocused) {final Rect focusOuter = outer.inflate(1);final Paint borderPaint = Paint()..color = focusColor..style = PaintingStyle.stroke..strokeWidth = 3.5;_drawBox(canvas, focusOuter, borderPaint, side, true);}}}1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545510 unmodified lines66676869707172737475767720 unmodified lines989910010110210310410510610710810911011111211311411511611711811933 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924022 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842852862872 unmodified lines29029129229329429529629729829930030130230330430530630730830931031128 unmodified lines34034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345440 unmodified lines4954964974984995005015025031 unmodified line50550650750850951051151251351451551651751851952011 unmodified lines5325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665676 unmodified lines57457557657757857958058158258358411 unmodified lines5965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316321 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'slider.dart';/// @docImport 'switch.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'constants.dart';import 'theme.dart';// Examples can assume:// bool _throwShotAway = false;// late StateSetter setState;// Eyeballed from a checkbox on a physical Macbook Pro running macOS version 14.5.const Color _kDisabledCheckColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(64, 0, 0, 0),darkColor: Color.fromARGB(64, 255, 255, 255),);const Color _kDisabledBorderColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(13, 0, 0, 0),darkColor: Color.fromARGB(13, 0, 0, 0),);const CupertinoDynamicColor _kDefaultBorderColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(255, 209, 209, 214),darkColor: Color.fromARGB(50, 128, 128, 128),);const CupertinoDynamicColor _kDefaultFillColor = CupertinoDynamicColor.withBrightness(color: CupertinoColors.activeBlue,darkColor: Color.fromARGB(255, 50, 100, 215),);const Color _kDefaultCheckColor = CupertinoDynamicColor.withBrightness(color: CupertinoColors.white,darkColor: Color.fromARGB(255, 222, 232, 248),);const double _kPressedOverlayOpacity = 0.15;// In dark mode, the fill color of a checkbox is an opacity gradient of the// background color.const List<double> _kDarkGradientOpacities = <double>[0.14, 0.29];const List<double> _kDisabledDarkGradientOpacities = <double>[0.08, 0.14];/// A macOS style checkbox.////// {@youtube 560 315 https://www.youtube.com/watch?v=ua54JU7k1Us}////// The checkbox itself does not maintain any state. Instead, when the state of/// the checkbox changes, the widget calls the [onChanged] callback. Most/// widgets that use a checkbox will listen for the [onChanged] callback and10 unmodified lines/// ([CupertinoSwitch] in Flutter) instead, or to find a creative custom/// solution.////// {@tool dartpad}/// This example shows a toggleable [CupertinoCheckbox].////// ** See code in examples/api/lib/cupertino/checkbox/cupertino_checkbox.0.dart **/// {@end-tool}////// See also:////// * [Checkbox], the Material Design equivalent.20 unmodified linesrequired this.value,this.tristate = false,required this.onChanged,this.mouseCursor,this.activeColor,@Deprecated('Use fillColor instead. ''fillColor now manages the background color in all states. ''This feature was deprecated after v3.24.0-0.2.pre.',)this.inactiveColor,this.fillColor,this.checkColor,this.focusColor,this.focusNode,this.autofocus = false,this.side,this.shape,this.semanticLabel,}) : assert(tristate || value != null);/// Whether this checkbox is checked.33 unmodified lines/// ```final ValueChanged<bool?>? onChanged;/// The cursor for a mouse pointer when it enters or is hovering over the/// widget.////// If [mouseCursor] is a [WidgetStateMouseCursor],/// [WidgetStateProperty.resolve] is used for the following [WidgetState]s:////// * [WidgetState.selected]./// * [WidgetState.focused]./// * [WidgetState.disabled].////// When [value] is null and [tristate] is true, [WidgetState.selected] is/// included as a state.////// If null, then [SystemMouseCursors.basic] is used when this checkbox is/// disabled. When the checkbox is enabled, [SystemMouseCursors.click] is used/// on Web, and [SystemMouseCursors.basic] is used on other platforms.////// See also:////// * [WidgetStateMouseCursor], a [MouseCursor] that implements/// [WidgetStateProperty] which is used in APIs that need to accept/// either a [MouseCursor] or a [WidgetStateProperty].final MouseCursor? mouseCursor;/// The color to use when this checkbox is checked.////// If [fillColor] returns a non-null color in the [WidgetState.selected]/// state, [fillColor] will be used instead of [activeColor].////// Defaults to [CupertinoColors.activeBlue].final Color? activeColor;/// {@template flutter.cupertino.CupertinoCheckbox.fillColor}/// The color used to fill this checkbox.////// Resolves in the following states:/// * [WidgetState.selected]./// * [WidgetState.hovered]./// * [WidgetState.focused]./// * [WidgetState.disabled].////// {@tool snippet}/// This example resolves the [fillColor] based on the current [WidgetState]/// of the [CupertinoCheckbox], providing a different [Color] when it is/// [WidgetState.disabled].////// ```dart/// CupertinoCheckbox(/// value: true,/// onChanged: (_){},/// fillColor: WidgetStateProperty.resolveWith<Color>((Set<WidgetState> states) {/// if (states.contains(WidgetState.disabled)) {/// return Colors.orange.withOpacity(.32);/// }/// return Colors.orange;/// })/// )/// ```/// {@end-tool}/// {@endtemplate}////// If [fillColor] resolves to null for the requested state, then the fill color/// falls back to [activeColor] if the state includes [WidgetState.selected],/// [CupertinoColors.white] at 50% opacity if checkbox is disabled,/// and [CupertinoColors.white] otherwise.final WidgetStateProperty<Color?>? fillColor;/// The color used if the checkbox is inactive.////// Currently [inactiveColor] is not used. Instead, [fillColor] controls the/// color of the background in all states, including when unselected.@Deprecated('Use fillColor instead. ''fillColor now manages the background color in all states. ''This feature was deprecated after v3.24.0-0.2.pre.',)final Color? inactiveColor;/// The color to use for the check icon when this checkbox is checked.////// If null, then the value of [CupertinoColors.white] is used if the checkbox/// is enabled. If the checkbox is disabled, a grey-black color is used.final Color? checkColor;/// If true, the checkbox's [value] can be true, false, or null.22 unmodified lines/// The color and width of the checkbox's border.////// This property can be a [WidgetStateBorderSide] that can/// specify different border color and widths depending on the/// checkbox's state.////// Resolves in the following states:/// * [WidgetState.pressed]./// * [WidgetState.selected]./// * [WidgetState.hovered]./// * [WidgetState.focused]./// * [WidgetState.disabled]./// * [WidgetState.error].////// If this property is not a [WidgetStateBorderSide] and it is/// non-null, then it is only rendered when the checkbox's value is/// false. The difference in interpretation is for backwards/// compatibility.////// If this property is null and the checkbox's value is false, then the side/// defaults to a one pixel wide grey-black border.final BorderSide? side;/// The shape of the checkbox.2 unmodified lines/// [RoundedRectangleBorder] with a circular corner radius of 4.0.final OutlinedBorder? shape;/// The semantic label for the checkbox that will be announced by screen readers.////// This is announced by assistive technologies (e.g TalkBack/VoiceOver).////// This label does not show in the UI.final String? semanticLabel;/// The width of a checkbox widget.static const double width = 14.0;@overrideState<CupertinoCheckbox> createState() => _CupertinoCheckboxState();}class _CupertinoCheckboxState extends State<CupertinoCheckbox>with TickerProviderStateMixin, ToggleableStateMixin {final _CheckboxPainter _painter = _CheckboxPainter();bool? _previousValue;28 unmodified lines@overridebool? get value => widget.value;WidgetStateProperty<Color> get _defaultFillColor {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if (states.contains(WidgetState.disabled)) {return CupertinoColors.white.withOpacity(0.5);}if (states.contains(WidgetState.selected)) {return widget.activeColor ?? CupertinoDynamicColor.resolve(_kDefaultFillColor, context);}return CupertinoColors.white;});}WidgetStateProperty<Color> get _defaultCheckColor {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if (states.contains(WidgetState.disabled) && states.contains(WidgetState.selected)) {return widget.checkColor ?? CupertinoDynamicColor.resolve(_kDisabledCheckColor, context);}if (states.contains(WidgetState.selected)) {return widget.checkColor ?? CupertinoDynamicColor.resolve(_kDefaultCheckColor, context);}return CupertinoColors.white;});}WidgetStateProperty<BorderSide> get _defaultSide {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if ((states.contains(WidgetState.selected) || states.contains(WidgetState.focused)) &&!states.contains(WidgetState.disabled)) {return const BorderSide(width: 0.0, color: CupertinoColors.transparent);}if (states.contains(WidgetState.disabled)) {return BorderSide(color: CupertinoDynamicColor.resolve(_kDisabledBorderColor, context));}return BorderSide(color: CupertinoDynamicColor.resolve(_kDefaultBorderColor, context));});}BorderSide? _resolveSide(BorderSide? side, Set<WidgetState> states) {if (side is WidgetStateBorderSide) {return WidgetStateProperty.resolveAs<BorderSide?>(side, states);}if (!states.contains(WidgetState.selected)) {return side;}return null;}@overrideWidget build(BuildContext context) {// Colors need to be resolved in selected and non selected states separately.// The `states` getter constructs a new set every time, making it safe to edit in place.final Set<WidgetState> activeStates = states..add(WidgetState.selected);final Set<WidgetState> inactiveStates = states..remove(WidgetState.selected);// Since the states getter always makes a new set, make a copy to use// throughout the lifecycle of this build method.final Set<WidgetState> currentStates = states;final Color effectiveActiveColor =widget.fillColor?.resolve(activeStates) ?? _defaultFillColor.resolve(activeStates);final Color effectiveInactiveColor =widget.fillColor?.resolve(inactiveStates) ?? _defaultFillColor.resolve(inactiveStates);final BorderSide effectiveBorderSide =_resolveSide(widget.side, currentStates) ?? _defaultSide.resolve(currentStates);final Color effectiveFocusOverlayColor =widget.focusColor ??HSLColor.fromColor(effectiveActiveColor.withOpacity(kCupertinoFocusColorOpacity)).withLightness(kCupertinoFocusColorBrightness).withSaturation(kCupertinoFocusColorSaturation).toColor();final WidgetStateProperty<MouseCursor> effectiveMouseCursor =WidgetStateProperty.resolveWith<MouseCursor>((Set<WidgetState> states) {return WidgetStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states) ??(kIsWeb && !states.contains(WidgetState.disabled)? SystemMouseCursors.click: SystemMouseCursors.basic);});return Semantics(label: widget.semanticLabel,checked: widget.value ?? false,mixed: widget.tristate ? widget.value == null : null,child: buildToggleable(mouseCursor: effectiveMouseCursor,focusNode: widget.focusNode,autofocus: widget.autofocus,size: const Size.square(kMinInteractiveDimensionCupertino),painter:_painter..position = position..reaction = reaction..focusColor = effectiveFocusOverlayColor..downPosition = downPosition..isFocused = currentStates.contains(WidgetState.focused)..isHovered = currentStates.contains(WidgetState.hovered)..activeColor = effectiveActiveColor..inactiveColor = effectiveInactiveColor..checkColor = _defaultCheckColor.resolve(currentStates)..value = value..previousValue = _previousValue..isActive = widget.onChanged != null..shape =widget.shape ?? RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0))..side = effectiveBorderSide..brightness = CupertinoTheme.of(context).brightness,),);}40 unmodified linesnotifyListeners();}BorderSide get side => _side!;BorderSide? _side;set side(BorderSide value) {if (_side == value) {return;}1 unmodified linenotifyListeners();}Brightness? get brightness => _brightness;Brightness? _brightness;set brightness(Brightness? value) {if (_brightness == value) {return;}_brightness = value;notifyListeners();}Rect _outerRectAt(Offset origin) {const double size = CupertinoCheckbox.width;final Rect rect = Rect.fromLTWH(origin.dx, origin.dy, size, size);11 unmodified linesreturn Paint()..color = checkColor..style = PaintingStyle.stroke..strokeWidth = 2.0..strokeCap = StrokeCap.round;}// Draw a gradient from the top to the bottom of the checkbox.void _drawFillGradient(Canvas canvas, Rect outer, Color topColor, Color bottomColor) {final LinearGradient fillGradient = LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,// Eyeballed from a checkbox on a physical Macbook Pro running macOS version 14.5.colors: <Color>[topColor, bottomColor],);final Paint gradientPaint = Paint()..shader = fillGradient.createShader(outer);canvas.drawPath(shape.getOuterPath(outer), gradientPaint);}void _drawBox(Canvas canvas, Rect outer, Paint paint, BorderSide? side, bool value) {// Draw a gradient in dark mode except when the checkbox is enabled and checked.if (brightness == Brightness.dark && !(isActive && value)) {_drawFillGradient(canvas,outer,paint.color.withOpacity(isActive ? _kDarkGradientOpacities[0] : _kDisabledDarkGradientOpacities[0],),paint.color.withOpacity(isActive ? _kDarkGradientOpacities[1] : _kDisabledDarkGradientOpacities[1],),);} else {canvas.drawPath(shape.getOuterPath(outer), paint);}if (side != null) {6 unmodified lines// The ratios for the offsets below were found from looking at the checkbox// examples on in the HIG docs. The distance from the needed point to the// edge was measured, then divided by the total width.const Offset start = Offset(CupertinoCheckbox.width * 0.22, CupertinoCheckbox.width * 0.54);const Offset mid = Offset(CupertinoCheckbox.width * 0.40, CupertinoCheckbox.width * 0.75);const Offset end = Offset(CupertinoCheckbox.width * 0.78, CupertinoCheckbox.width * 0.25);path.moveTo(origin.dx + start.dx, origin.dy + start.dy);path.lineTo(origin.dx + mid.dx, origin.dy + mid.dy);path.moveTo(origin.dx + mid.dx, origin.dy + mid.dy);path.lineTo(origin.dx + end.dx, origin.dy + end.dy);canvas.drawPath(path, paint);11 unmodified linesvoid paint(Canvas canvas, Size size) {final Paint strokePaint = _createStrokePaint();final Offset origin = size / 2.0 - const Size.square(CupertinoCheckbox.width) / 2.0 as Offset;final Rect outer = _outerRectAt(origin);final Paint paint = Paint()..color = _colorAt(value ?? true);switch (value) {case false:_drawBox(canvas, outer, paint, side, value ?? true);case true:_drawBox(canvas, outer, paint, side, value ?? true);_drawCheck(canvas, origin, strokePaint);case null:_drawBox(canvas, outer, paint, side, value ?? true);_drawDash(canvas, origin, strokePaint);}// The checkbox's opacity changes when pressed.if (downPosition != null) {final Paint pressedPaint =Paint()..color =brightness == Brightness.light? CupertinoColors.black.withOpacity(_kPressedOverlayOpacity): CupertinoColors.white.withOpacity(_kPressedOverlayOpacity);canvas.drawPath(shape.getOuterPath(outer), pressedPaint);}if (isFocused) {final Rect focusOuter = outer.inflate(1);final Paint borderPaint =Paint()..color = focusColor..style = PaintingStyle.stroke..strokeWidth = 3.5;_drawBox(canvas, focusOuter, borderPaint, side, value ?? true);}}}
1 unmodified line234567853 unmodified lines626364656667683 unmodified lines7273747576777879808128 unmodified lines11011111211311411511629 unmodified lines14614714814915015115215349 unmodified lines20320420520620720820921049 unmodified lines260261262263264265266267125 unmodified lines393394395396397398399198 unmodified lines598599600601602603604130 unmodified lines73573673773873974074131 unmodified lines7737747757767777787797807817827837847857867877883 unmodified lines7927937947957967977987998008018028038048058068077 unmodified lines8158168178188198208218228238241 unmodified line82682782882983083183283383499 unmodified lines93493593693793893994094194210 unmodified lines95395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498527 unmodified lines10131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104823 unmodified lines107210731074107510761077107810791080108110821083108410851086108710 unmodified lines1098109911001101110211031104110511061107110811091110111111121113111411151116111722 unmodified lines11401141114211431144114511461147114811491150115111521153115411551 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:ui' show Brightness, Color;import '../../foundation.dart';import '../widgets/basic.dart';53 unmodified lines////// See also:////// * [material.Colors.white], the same color, in the Material Design palette./// * [black], opaque black in the [CupertinoColors] palette.static const Color white = Color(0xFFFFFFFF);3 unmodified lines////// See also:////// * [material.Colors.black], the same color, in the Material Design palette./// * [white], opaque white in the [CupertinoColors] palette.static const Color black = Color(0xFF000000);/// Used in iOS 10 for light background fills such as the chat bubble background.////// This is SystemLightGrayColor in the iOS palette.28 unmodified lines/// or the foreground red theme in various native apps such as HealthKit.////// This is SystemRed in the iOS palette.static const Color destructiveRed = systemRed;/// A blue color that can adapt to the given [BuildContext].///29 unmodified lines////// * [UIColor.systemMint](https://developer.apple.com/documentation/uikit/uicolor/3852741-systemmint),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemMint =CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemMint',color: Color.fromARGB(255, 0, 199, 190),darkColor: Color.fromARGB(255, 99, 230, 226),49 unmodified lines////// * [UIColor.systemBrown](https://developer.apple.com/documentation/uikit/uicolor/3173142-systembrown),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemBrown =CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemBrown',color: Color.fromARGB(255, 162, 132, 94),darkColor: Color.fromARGB(255, 172, 142, 104),49 unmodified lines////// * [UIColor.systemCyan](https://developer.apple.com/documentation/uikit/uicolor/3852740-systemcyan),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemCyan =CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemCyan',color: Color.fromARGB(255, 50, 173, 230),darkColor: Color.fromARGB(255, 100, 210, 255),125 unmodified linesdarkElevatedColor: Color.fromARGB(153, 235, 235, 245),highContrastElevatedColor: Color.fromARGB(173, 60, 60, 67),darkHighContrastElevatedColor: Color.fromARGB(173, 235, 235, 245),);/// The color for text labels containing tertiary content, equivalent to/// [UIColor.tertiaryLabel](https://developer.apple.com/documentation/uikit/uicolor/3173153-tertiarylabel).198 unmodified lineshighContrastColor: Color.fromARGB(94, 60, 60, 67),darkHighContrastColor: Color.fromARGB(173, 84, 84, 88),elevatedColor: Color.fromARGB(73, 60, 60, 67),darkElevatedColor: Color.fromARGB(153, 84, 84, 88),highContrastElevatedColor: Color.fromARGB(94, 60, 60, 67),darkHighContrastElevatedColor: Color.fromARGB(173, 84, 84, 88),);130 unmodified lines/// * [CupertinoTheme.of], a static method that retrieves the ambient [CupertinoThemeData],/// and then resolves [CupertinoDynamicColor]s used in the retrieved data.@immutableclass CupertinoDynamicColor extends Color with Diagnosticable {/// Creates an adaptive [Color] that changes its effective color based on the/// [BuildContext] given. The default effective color is [color].const CupertinoDynamicColor({31 unmodified linesrequired Color highContrastColor,required Color darkHighContrastColor,}) : this(debugLabel: debugLabel,color: color,darkColor: darkColor,highContrastColor: highContrastColor,darkHighContrastColor: darkHighContrastColor,elevatedColor: color,darkElevatedColor: darkColor,highContrastElevatedColor: highContrastColor,darkHighContrastElevatedColor: darkHighContrastColor,);/// Creates an adaptive [Color] that changes its effective color based on the given/// [BuildContext]'s brightness (from [MediaQueryData.platformBrightness] or3 unmodified linesrequired Color color,required Color darkColor,}) : this(debugLabel: debugLabel,color: color,darkColor: darkColor,highContrastColor: color,darkHighContrastColor: darkColor,elevatedColor: color,darkElevatedColor: darkColor,highContrastElevatedColor: color,darkHighContrastElevatedColor: darkColor,);const CupertinoDynamicColor._(this._effectiveColor,7 unmodified linesthis.darkHighContrastElevatedColor,this._debugResolveContext,this._debugLabel,) : // The super constructor has to be called with a dummy value in order to mark// this constructor const.// The field `value` is overridden in the class implementation.super(0);/// The current effective color.///1 unmodified line/// resolved.final Color _effectiveColor;@overrideint get value => _effectiveColor.value;final String? _debugLabel;final Element? _debugResolveContext;99 unmodified lines/// * [maybeResolve], which is similar to this function, but will allow a/// null `resolvable` color.static Color resolve(Color resolvable, BuildContext context) {return (resolvable is CupertinoDynamicColor)? resolvable.resolveFrom(context): resolvable;}/// Resolves the given [Color] by calling [resolveFrom].10 unmodified lines/// * [resolve], which is similar to this function, but returns a/// non-nullable value, and does not allow a null `resolvable` color.static Color? maybeResolve(Color? resolvable, BuildContext context) {if (resolvable == null) {return null;}return (resolvable is CupertinoDynamicColor)? resolvable.resolveFrom(context): resolvable;}bool get _isPlatformBrightnessDependent {return color != darkColor|| elevatedColor != darkElevatedColor|| highContrastColor != darkHighContrastColor|| highContrastElevatedColor != darkHighContrastElevatedColor;}bool get _isHighContrastDependent {return color != highContrastColor|| darkColor != darkHighContrastColor|| elevatedColor != highContrastElevatedColor|| darkElevatedColor != darkHighContrastElevatedColor;}bool get _isInterfaceElevationDependent {return color != elevatedColor|| darkColor != darkElevatedColor|| highContrastColor != highContrastElevatedColor|| darkHighContrastColor != darkHighContrastElevatedColor;}/// Resolves this [CupertinoDynamicColor] using the provided [BuildContext].27 unmodified lines/// brightness, normal contrast, [CupertinoUserInterfaceLevelData.base]/// elevation level).CupertinoDynamicColor resolveFrom(BuildContext context) {Brightness brightness = Brightness.light;if (_isPlatformBrightnessDependent) {brightness = CupertinoTheme.maybeBrightnessOf(context) ?? Brightness.light;}bool isHighContrastEnabled = false;if (_isHighContrastDependent) {isHighContrastEnabled = MediaQuery.maybeHighContrastOf(context) ?? false;}final CupertinoUserInterfaceLevelData level = _isInterfaceElevationDependent? CupertinoUserInterfaceLevel.maybeOf(context) ?? CupertinoUserInterfaceLevelData.base: CupertinoUserInterfaceLevelData.base;final Color resolved;switch (brightness) {case Brightness.light:switch (level) {case CupertinoUserInterfaceLevelData.base:resolved = isHighContrastEnabled ? highContrastColor : color;case CupertinoUserInterfaceLevelData.elevated:resolved = isHighContrastEnabled ? highContrastElevatedColor : elevatedColor;}case Brightness.dark:switch (level) {case CupertinoUserInterfaceLevelData.base:resolved = isHighContrastEnabled ? darkHighContrastColor : darkColor;case CupertinoUserInterfaceLevelData.elevated:resolved = isHighContrastEnabled ? darkHighContrastElevatedColor : darkElevatedColor;}}Element? debugContext;assert(() {23 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is CupertinoDynamicColor&& other.value == value&& other.color == color&& other.darkColor == darkColor&& other.highContrastColor == highContrastColor&& other.darkHighContrastColor == darkHighContrastColor&& other.elevatedColor == elevatedColor&& other.darkElevatedColor == darkElevatedColor&& other.highContrastElevatedColor == highContrastElevatedColor&& other.darkHighContrastElevatedColor == darkHighContrastElevatedColor;}@override10 unmodified lines);@overrideString toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {String toString(String name, Color color) {final String marker = color == _effectiveColor ? '*' : '';return '$marker$name = $color$marker';}final List<String> xs = <String>[toString('color', color),if (_isPlatformBrightnessDependent) toString('darkColor', darkColor),if (_isHighContrastDependent) toString('highContrastColor', highContrastColor),if (_isPlatformBrightnessDependent && _isHighContrastDependent) toString('darkHighContrastColor', darkHighContrastColor),if (_isInterfaceElevationDependent) toString('elevatedColor', elevatedColor),if (_isPlatformBrightnessDependent && _isInterfaceElevationDependent) toString('darkElevatedColor', darkElevatedColor),if (_isHighContrastDependent && _isInterfaceElevationDependent) toString('highContrastElevatedColor', highContrastElevatedColor),if (_isPlatformBrightnessDependent && _isHighContrastDependent && _isInterfaceElevationDependent) toString('darkHighContrastElevatedColor', darkHighContrastElevatedColor),];return '${_debugLabel ?? objectRuntimeType(this, 'CupertinoDynamicColor')}(${xs.join(', ')}, resolved by: ${_debugResolveContext?.widget ?? "UNRESOLVED"})';22 unmodified linesproperties.add(createCupertinoColorProperty('darkElevatedColor', darkElevatedColor));}if (_isHighContrastDependent && _isInterfaceElevationDependent) {properties.add(createCupertinoColorProperty('highContrastElevatedColor', highContrastElevatedColor));}if (_isPlatformBrightnessDependent && _isHighContrastDependent && _isInterfaceElevationDependent) {properties.add(createCupertinoColorProperty('darkHighContrastElevatedColor', darkHighContrastElevatedColor));}if (_debugResolveContext != null) {properties.add(DiagnosticsProperty<Element>('last resolved', _debugResolveContext));}}}/// Creates a diagnostics property for [CupertinoDynamicColor].1 unmodified line23456789101112131453 unmodified lines686970717273743 unmodified lines787980818283848586878889909192939428 unmodified lines12312412512612712812929 unmodified lines15916016116216316416549 unmodified lines21521621721821922022149 unmodified lines271272273274275276277125 unmodified lines403404405406407408409198 unmodified lines608609610611612613614130 unmodified lines74574674774874975075131 unmodified lines7837847857867877887897907917927937947957967977983 unmodified lines8028038048058068078088098108118128138148158168177 unmodified lines8258268278288298308311 unmodified line83383483583683783899 unmodified lines93893994094194294394410 unmodified lines95595695795895996096196296396496596696796896997097197297397497597697797897998098198227 unmodified lines101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104023 unmodified lines106410651066106710681069107010711072107310741075107610771078107910 unmodified lines10901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111622 unmodified lines11391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'button.dart';/// @docImport 'nav_bar.dart';library;import 'dart:ui' show Brightness, Color, ColorSpace;import '../../foundation.dart';import '../widgets/basic.dart';53 unmodified lines////// See also:////// * [Colors.white], the same color, in the Material Design palette./// * [black], opaque black in the [CupertinoColors] palette.static const Color white = Color(0xFFFFFFFF);3 unmodified lines////// See also:////// * [Colors.black], the same color, in the Material Design palette./// * [white], opaque white in the [CupertinoColors] palette.static const Color black = Color(0xFF000000);/// A fully-transparent color, completely invisible.////// See also:////// * [Colors.transparent], the same color, in the Material Design palette.static const Color transparent = Color(0x00000000);/// Used in iOS 10 for light background fills such as the chat bubble background.////// This is SystemLightGrayColor in the iOS palette.28 unmodified lines/// or the foreground red theme in various native apps such as HealthKit.////// This is SystemRed in the iOS palette.static const CupertinoDynamicColor destructiveRed = systemRed;/// A blue color that can adapt to the given [BuildContext].///29 unmodified lines////// * [UIColor.systemMint](https://developer.apple.com/documentation/uikit/uicolor/3852741-systemmint),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemMint = CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemMint',color: Color.fromARGB(255, 0, 199, 190),darkColor: Color.fromARGB(255, 99, 230, 226),49 unmodified lines////// * [UIColor.systemBrown](https://developer.apple.com/documentation/uikit/uicolor/3173142-systembrown),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemBrown = CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemBrown',color: Color.fromARGB(255, 162, 132, 94),darkColor: Color.fromARGB(255, 172, 142, 104),49 unmodified lines////// * [UIColor.systemCyan](https://developer.apple.com/documentation/uikit/uicolor/3852740-systemcyan),/// the `UIKit` equivalent.static const CupertinoDynamicColor systemCyan = CupertinoDynamicColor.withBrightnessAndContrast(debugLabel: 'systemCyan',color: Color.fromARGB(255, 50, 173, 230),darkColor: Color.fromARGB(255, 100, 210, 255),125 unmodified linesdarkElevatedColor: Color.fromARGB(153, 235, 235, 245),highContrastElevatedColor: Color.fromARGB(173, 60, 60, 67),darkHighContrastElevatedColor: Color.fromARGB(173, 235, 235, 245),);/// The color for text labels containing tertiary content, equivalent to/// [UIColor.tertiaryLabel](https://developer.apple.com/documentation/uikit/uicolor/3173153-tertiarylabel).198 unmodified lineshighContrastColor: Color.fromARGB(94, 60, 60, 67),darkHighContrastColor: Color.fromARGB(173, 84, 84, 88),elevatedColor: Color.fromARGB(73, 60, 60, 67),darkElevatedColor: Color.fromARGB(153, 210, 210, 210),highContrastElevatedColor: Color.fromARGB(94, 60, 60, 67),darkHighContrastElevatedColor: Color.fromARGB(173, 84, 84, 88),);130 unmodified lines/// * [CupertinoTheme.of], a static method that retrieves the ambient [CupertinoThemeData],/// and then resolves [CupertinoDynamicColor]s used in the retrieved data.@immutableclass CupertinoDynamicColor with Diagnosticable implements Color {/// Creates an adaptive [Color] that changes its effective color based on the/// [BuildContext] given. The default effective color is [color].const CupertinoDynamicColor({31 unmodified linesrequired Color highContrastColor,required Color darkHighContrastColor,}) : this(debugLabel: debugLabel,color: color,darkColor: darkColor,highContrastColor: highContrastColor,darkHighContrastColor: darkHighContrastColor,elevatedColor: color,darkElevatedColor: darkColor,highContrastElevatedColor: highContrastColor,darkHighContrastElevatedColor: darkHighContrastColor,);/// Creates an adaptive [Color] that changes its effective color based on the given/// [BuildContext]'s brightness (from [MediaQueryData.platformBrightness] or3 unmodified linesrequired Color color,required Color darkColor,}) : this(debugLabel: debugLabel,color: color,darkColor: darkColor,highContrastColor: color,darkHighContrastColor: darkColor,elevatedColor: color,darkElevatedColor: darkColor,highContrastElevatedColor: color,darkHighContrastElevatedColor: darkColor,);const CupertinoDynamicColor._(this._effectiveColor,7 unmodified linesthis.darkHighContrastElevatedColor,this._debugResolveContext,this._debugLabel,);/// The current effective color.///1 unmodified line/// resolved.final Color _effectiveColor;final String? _debugLabel;final Element? _debugResolveContext;99 unmodified lines/// * [maybeResolve], which is similar to this function, but will allow a/// null `resolvable` color.static Color resolve(Color resolvable, BuildContext context) {return (resolvable is CupertinoDynamicColor) ? resolvable.resolveFrom(context) : resolvable;}/// Resolves the given [Color] by calling [resolveFrom].10 unmodified lines/// * [resolve], which is similar to this function, but returns a/// non-nullable value, and does not allow a null `resolvable` color.static Color? maybeResolve(Color? resolvable, BuildContext context) {return (resolvable is CupertinoDynamicColor) ? resolvable.resolveFrom(context) : resolvable;}bool get _isPlatformBrightnessDependent {return color != darkColor ||elevatedColor != darkElevatedColor ||highContrastColor != darkHighContrastColor ||highContrastElevatedColor != darkHighContrastElevatedColor;}bool get _isHighContrastDependent {return color != highContrastColor ||darkColor != darkHighContrastColor ||elevatedColor != highContrastElevatedColor ||darkElevatedColor != darkHighContrastElevatedColor;}bool get _isInterfaceElevationDependent {return color != elevatedColor ||darkColor != darkElevatedColor ||highContrastColor != highContrastElevatedColor ||darkHighContrastColor != darkHighContrastElevatedColor;}/// Resolves this [CupertinoDynamicColor] using the provided [BuildContext].27 unmodified lines/// brightness, normal contrast, [CupertinoUserInterfaceLevelData.base]/// elevation level).CupertinoDynamicColor resolveFrom(BuildContext context) {final Brightness brightness =_isPlatformBrightnessDependent? CupertinoTheme.maybeBrightnessOf(context) ?? Brightness.light: Brightness.light;final CupertinoUserInterfaceLevelData level =_isInterfaceElevationDependent? CupertinoUserInterfaceLevel.maybeOf(context) ?? CupertinoUserInterfaceLevelData.base: CupertinoUserInterfaceLevelData.base;final bool highContrast =_isHighContrastDependent && (MediaQuery.maybeHighContrastOf(context) ?? false);final Color resolved = switch ((brightness, level, highContrast)) {(Brightness.light, CupertinoUserInterfaceLevelData.base, false) => color,(Brightness.light, CupertinoUserInterfaceLevelData.base, true) => highContrastColor,(Brightness.light, CupertinoUserInterfaceLevelData.elevated, false) => elevatedColor,(Brightness.light, CupertinoUserInterfaceLevelData.elevated, true) =>highContrastElevatedColor,(Brightness.dark, CupertinoUserInterfaceLevelData.base, false) => darkColor,(Brightness.dark, CupertinoUserInterfaceLevelData.base, true) => darkHighContrastColor,(Brightness.dark, CupertinoUserInterfaceLevelData.elevated, false) => darkElevatedColor,(Brightness.dark, CupertinoUserInterfaceLevelData.elevated, true) =>darkHighContrastElevatedColor,};Element? debugContext;assert(() {23 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is CupertinoDynamicColor &&other.value == value &&other.color == color &&other.darkColor == darkColor &&other.highContrastColor == highContrastColor &&other.darkHighContrastColor == darkHighContrastColor &&other.elevatedColor == elevatedColor &&other.darkElevatedColor == darkElevatedColor &&other.highContrastElevatedColor == highContrastElevatedColor &&other.darkHighContrastElevatedColor == darkHighContrastElevatedColor;}@override10 unmodified lines);@overrideString toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {String toString(String name, Color color) {final String marker = color == _effectiveColor ? '*' : '';return '$marker$name = $color$marker';}final List<String> xs = <String>[toString('color', color),if (_isPlatformBrightnessDependent) toString('darkColor', darkColor),if (_isHighContrastDependent) toString('highContrastColor', highContrastColor),if (_isPlatformBrightnessDependent && _isHighContrastDependent)toString('darkHighContrastColor', darkHighContrastColor),if (_isInterfaceElevationDependent) toString('elevatedColor', elevatedColor),if (_isPlatformBrightnessDependent && _isInterfaceElevationDependent)toString('darkElevatedColor', darkElevatedColor),if (_isHighContrastDependent && _isInterfaceElevationDependent)toString('highContrastElevatedColor', highContrastElevatedColor),if (_isPlatformBrightnessDependent &&_isHighContrastDependent &&_isInterfaceElevationDependent)toString('darkHighContrastElevatedColor', darkHighContrastElevatedColor),];return '${_debugLabel ?? objectRuntimeType(this, 'CupertinoDynamicColor')}(${xs.join(', ')}, resolved by: ${_debugResolveContext?.widget ?? "UNRESOLVED"})';22 unmodified linesproperties.add(createCupertinoColorProperty('darkElevatedColor', darkElevatedColor));}if (_isHighContrastDependent && _isInterfaceElevationDependent) {properties.add(createCupertinoColorProperty('highContrastElevatedColor', highContrastElevatedColor),);}if (_isPlatformBrightnessDependent &&_isHighContrastDependent &&_isInterfaceElevationDependent) {properties.add(createCupertinoColorProperty('darkHighContrastElevatedColor',darkHighContrastElevatedColor,),);}if (_debugResolveContext != null) {properties.add(DiagnosticsProperty<Element>('last resolved', _debugResolveContext));}}@overrideint get value => _effectiveColor.value;@overrideint toARGB32() => value;@overrideint get alpha => _effectiveColor.alpha;@overrideint get blue => _effectiveColor.blue;@overridedouble computeLuminance() => _effectiveColor.computeLuminance();@overrideint get green => _effectiveColor.green;@overridedouble get opacity => _effectiveColor.opacity;@overrideint get red => _effectiveColor.red;@overrideColor withAlpha(int a) => _effectiveColor.withAlpha(a);@overrideColor withBlue(int b) => _effectiveColor.withBlue(b);@overrideColor withGreen(int g) => _effectiveColor.withGreen(g);@overrideColor withOpacity(double opacity) => _effectiveColor.withOpacity(opacity);@overrideColor withRed(int r) => _effectiveColor.withRed(r);@overridedouble get a => _effectiveColor.a;@overridedouble get r => _effectiveColor.r;@overridedouble get g => _effectiveColor.g;@overridedouble get b => _effectiveColor.b;@overrideColorSpace get colorSpace => _effectiveColor.colorSpace;@overrideColor withValues({double? alpha,double? red,double? green,double? blue,ColorSpace? colorSpace,}) => _effectiveColor.withValues(alpha: alpha,red: red,green: green,blue: blue,colorSpace: colorSpace,);}/// Creates a diagnostics property for [CupertinoDynamicColor].
1 unmodified line2345677 unmodified lines1516171 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// The minimum dimension of any interactive region according to the iOS Human/// Interface Guidelines.///7 unmodified lines/// * [kMinInteractiveDimension]/// * <https://developer.apple.com/ios/human-interface-guidelines/visual-design/adaptivity-and-layout/>const double kMinInteractiveDimensionCupertino = 44.0;1 unmodified line23456789101112131415161718197 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293941 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'checkbox.dart';/// @docImport 'radio.dart';/// @docImport 'switch.dart';/// @docImport 'text_theme.dart';library;import 'package:flutter/widgets.dart';import 'button.dart';/// The minimum dimension of any interactive region according to the iOS Human/// Interface Guidelines.///7 unmodified lines/// * [kMinInteractiveDimension]/// * <https://developer.apple.com/ios/human-interface-guidelines/visual-design/adaptivity-and-layout/>const double kMinInteractiveDimensionCupertino = 44.0;/// The relative values needed to transform a color to it's equivalent focus/// outline color.////// These are used to draw a focus ring around [CupertinoSwitch],/// [CupertinoCheckbox], [CupertinoRadio] and [CupertinoButton].////// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/focus-and-selection/>const double kCupertinoFocusColorOpacity = 0.80,kCupertinoFocusColorBrightness = 0.69,kCupertinoFocusColorSaturation = 0.835;/// Opacity values for the background of a [CupertinoButton.tinted].////// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS>const double kCupertinoButtonTintedOpacityLight = 0.12, kCupertinoButtonTintedOpacityDark = 0.26;/// The default value for [IconThemeData.size] of [CupertinoButton.child].////// Set to match the most-frequent size of icons in iOS (matches md/lg).////// Used only when the [CupertinoTextThemeData.actionTextStyle] or [CupertinoTextThemeData.actionSmallTextStyle]/// has a null [TextStyle.fontSize].const double kCupertinoButtonDefaultIconSize = 20.0;/// The padding values for the different [CupertinoButtonSize]s.////// Based on the iOS (17) [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS).const Map<CupertinoButtonSize, EdgeInsetsGeometry> kCupertinoButtonPadding =<CupertinoButtonSize, EdgeInsetsGeometry>{CupertinoButtonSize.small: EdgeInsets.symmetric(vertical: 6, horizontal: 12),CupertinoButtonSize.medium: EdgeInsets.symmetric(vertical: 10, horizontal: 15),CupertinoButtonSize.large: EdgeInsets.symmetric(vertical: 16, horizontal: 20),};/// The border radius values for the different [CupertinoButtonSize]s.////// Based on the iOS (17) [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS).final Map<CupertinoButtonSize, BorderRadius> kCupertinoButtonSizeBorderRadius =<CupertinoButtonSize, BorderRadius>{CupertinoButtonSize.small: BorderRadius.circular(40),CupertinoButtonSize.medium: BorderRadius.circular(40),CupertinoButtonSize.large: BorderRadius.circular(12),};/// The minimum size of a [CupertinoButton] based on the [CupertinoButtonSize].////// Based on the iOS (17) [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS).const Map<CupertinoButtonSize, double> kCupertinoButtonMinSize = <CupertinoButtonSize, double>{CupertinoButtonSize.small: 28,CupertinoButtonSize.medium: 32,CupertinoButtonSize.large: 44,};/// The distance a button needs to be moved after being pressed for its opacity to change.////// The opacity changes when the position moved is this distance away from the button./// This variable is effective on mobile platforms. For desktop platforms, a distance of 0 is used.////// This value was obtained through actual testing on an iOS 18.1 simulator.const double kCupertinoButtonTapMoveSlop = 70.0;
1 unmodified line2345675 unmodified lines13141516171819202122232425261 unmodified line2829303132333435363738394041424344454647481 unmodified line50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051 unmodified line10710810911011111211311411511611720 unmodified lines1381391401411421431441451461471489 unmodified lines15815916016116216316416527 unmodified lines19319419519619719819920020120220344 unmodified lines24824925025125225346 unmodified lines30030130230330430530630730830931042 unmodified lines35335435535635735835936036136236336436536636736836937037137237337437537637737837938014 unmodified lines3953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684 unmodified lines4734744754764774788 unmodified lines48748848949049149249349449549649749849950050150215 unmodified lines5185195205215225235245256 unmodified lines5325335345355365373 unmodified lines54154254354454554654754854955055155255355455555655755837 unmodified lines59659759859960060160233 unmodified lines63663763863964064164264364464574 unmodified lines7207217227237247253 unmodified lines72973073173273373473573673726 unmodified lines7647657667677687697707717727737747757767777787797807817827837847857867877887897907917924 unmodified lines79779879980080180217 unmodified lines8208218228238248258268278288298308314 unmodified lines83683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587612 unmodified lines8898908918928938949 unmodified lines9049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369371 unmodified line9399409419429439449459469479489499509519529539549559569572 unmodified lines96096196296396496596696749 unmodified lines1017101810191020102110221023102410251026102710281029103010313 unmodified lines10351036103710381039104010412 unmodified lines10441045104610471048104910501051105210531054105510561057105835 unmodified lines10941095109610971098109921 unmodified lines11211122112311241125112611275 unmodified lines113311341135113611371138113911401 unmodified line11421143114411451146114711481149115011519 unmodified lines1161116211631164116511661167116811696 unmodified lines11761177117811791180118111821183118414 unmodified lines1199120012011202120312041205120612071208120912101211121210 unmodified lines1223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212735 unmodified lines12791280128112821283128412851286128712881 unmodified line12901291129212931294129512961297129812997 unmodified lines13071308130913101311131213131314131513161317131813191320132113221 unmodified line13241325132613271328132913301331133213334 unmodified lines13381339134013411342134313441345134613471348134913501351135213531354135513564 unmodified lines136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014015 unmodified lines1407140814091410141114121413141414151416141714181419142014213 unmodified lines1425142614271428142914301431143214331434143514361437143814391440144114421443144414453 unmodified lines144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;import 'dart:ui' as ui;5 unmodified linesimport 'colors.dart';import 'localizations.dart';// The scale of the child at the time that the CupertinoContextMenu opens.// This value was eyeballed from a physical device running iOS 13.1.2.const double _kOpenScale = 1.15;// The ratio for the borderRadius of the context menu preview image. This value// was eyeballed by overlapping the CupertinoContextMenu with a context menu// from iOS 16.0 in the XCode iPhone simulator.const double _previewBorderRadiusRatio = 12.0;// The duration of the transition used when a modal popup is shown. Eyeballed1 unmodified lineconst Duration _kModalPopupTransitionDuration = Duration(milliseconds: 335);// The duration it takes for the CupertinoContextMenu to open.// This value was eyeballed from the XCode simulator running iOS 16.0.const Duration _previewLongPressTimeout = Duration(milliseconds: 800);// The total length of the combined animations until the menu is fully open.final int _animationDuration =_previewLongPressTimeout.inMilliseconds + _kModalPopupTransitionDuration.inMilliseconds;// The final box shadow for the opening child widget.// This value was eyeballed from the XCode simulator running iOS 16.0.const List<BoxShadow> _endBoxShadow = <BoxShadow>[BoxShadow(color: Color(0x40000000),blurRadius: 10.0,spreadRadius: 0.5,),];const Color _borderColor = CupertinoDynamicColor.withBrightness(1 unmodified linedarkColor: Color(0xFF57585A),);typedef _DismissCallback = void Function(BuildContext context,double scale,double opacity,);/// A function that produces the preview when the CupertinoContextMenu is open.////// Called every time the animation value changes.typedef ContextMenuPreviewBuilder = Widget Function(BuildContext context,Animation<double> animation,Widget child,);/// A function that builds the child and handles the transition between the/// default child and the preview when the CupertinoContextMenu is open.typedef CupertinoContextMenuBuilder = Widget Function(BuildContext context,Animation<double> animation,);// Given a GlobalKey, return the Rect of the corresponding RenderBox's// paintBounds in global coordinates.Rect _getRect(GlobalKey globalKey) {assert(globalKey.currentContext != null);final RenderBox renderBoxContainer = globalKey.currentContext!.findRenderObject()! as RenderBox;return Rect.fromPoints(renderBoxContainer.localToGlobal(renderBoxContainer.paintBounds.topLeft,), renderBoxContainer.localToGlobal(renderBoxContainer.paintBounds.bottomRight));}// The context menu arranges itself slightly differently based on the location// on the screen of [CupertinoContextMenu.child] before the// [CupertinoContextMenu] opens.enum _ContextMenuLocation {center,left,right,}/// A full-screen modal route that opens when the [child] is long-pressed.////// When open, the [CupertinoContextMenu] shows the child, or the widget returned/// by [previewBuilder] if given, in a large full-screen [Overlay] with a list/// of buttons specified by [actions]. The child/preview is placed in an/// [Expanded] widget so that it will grow to fill the Overlay if its size is/// unconstrained.////// When closed, the [CupertinoContextMenu] displays the child as if the/// [CupertinoContextMenu] were not there. Sizing and positioning is unaffected.1 unmodified line/// background or by calling `Navigator.pop(context)`. Unlike [PopupRoute], it can/// also be closed by swiping downwards.////// The [previewBuilder] parameter is most commonly used to display a slight/// variation of [child]. See [previewBuilder] for an example of rounding the/// child's corners and allowing its aspect ratio to expand, similar to the/// Photos app on iOS.////// {@tool dartpad}/// This sample shows a very simple [CupertinoContextMenu] for the Flutter logo./// Long press on it to open.20 unmodified linesrequired this.actions,required Widget this.child,this.enableHapticFeedback = false,@Deprecated('Use CupertinoContextMenu.builder instead. ''This feature was deprecated after v3.4.0-34.1.pre.',)this.previewBuilder = _defaultPreviewBuilder,}) : assert(actions.isNotEmpty),builder = ((BuildContext context, Animation<double> animation) => child);9 unmodified linesrequired this.builder,this.enableHapticFeedback = false,}) : assert(actions.isNotEmpty),child = null,previewBuilder = null;/// Exposes the default border radius for matching iOS 16.0 behavior. This/// value was eyeballed from the iOS simulator running iOS 16.0.27 unmodified lines////// final Animation<Decoration> boxDecorationAnimation = DecorationTween(/// begin: const BoxDecoration(/// color: Color(0xFFFFFFFF),/// boxShadow: <BoxShadow>[],/// ),/// end: const BoxDecoration(/// color: Color(0xFFFFFFFF),/// boxShadow: CupertinoContextMenu.kEndBoxShadow,/// ),/// ).animate(44 unmodified linesstatic final double animationOpensAt =_previewLongPressTimeout.inMilliseconds / _animationDuration;/// A function that returns a widget to be used alternatively from [child].////// The widget returned by the function will be shown at all times: when the46 unmodified lines////// final Animation<Decoration> boxDecorationAnimation = DecorationTween(/// begin: const BoxDecoration(/// color: Color(0xFFFFFFFF),/// boxShadow: <BoxShadow>[],/// ),/// end: const BoxDecoration(/// color: Color(0xFFFFFFFF),/// boxShadow: CupertinoContextMenu.kEndBoxShadow,/// ),/// ).animate(42 unmodified lines/// {@end-tool}final CupertinoContextMenuBuilder builder;/// The default preview builder if none is provided. It makes a rectangle/// around the child widget with rounded borders, matching the iOS 16 opened/// context menu eyeballed on the XCode iOS simulator.static Widget _defaultPreviewBuilder(BuildContext context, Animation<double> animation, Widget child) {return FittedBox(fit: BoxFit.cover,child: ClipRRect(borderRadius: BorderRadius.circular(_previewBorderRadiusRatio * animation.value),child: child,),);}// TODO(mitchgoodwin): deprecate [child] with builder refactor https://github.com/flutter/flutter/issues/116306/// The widget that can be "opened" with the [CupertinoContextMenu].////// When the [CupertinoContextMenu] is long-pressed, the menu will open and/// this widget (or the widget returned by [previewBuilder], if provided) will/// be moved to the new route and placed inside of an [Expanded] widget. This/// allows the child to resize to fit in its place in the new route, if it/// doesn't size itself.////// When the [CupertinoContextMenu] is "closed", this widget acts like a/// [Container], i.e. it does not constrain its child's size or affect its14 unmodified lines/// Defaults to false.final bool enableHapticFeedback;/// A function that returns an alternative widget to show when the/// [CupertinoContextMenu] is open.////// If not specified, [child] will be shown.////// The preview is often used to show a slight variation of the [child]. For/// example, the child could be given rounded corners in the preview but have/// sharp corners when in the page.////// In addition to the current [BuildContext], the function is also called/// with an [Animation] and the [child]. The animation goes from 0 to 1 when/// the CupertinoContextMenu opens, and from 1 to 0 when it closes, and it can/// be used to animate the preview in sync with this opening and closing. The/// child parameter provides access to the child displayed when the/// CupertinoContextMenu is closed.////// {@tool snippet}////// Below is an example of using [previewBuilder] to show an image tile that's/// similar to each tile in the iOS iPhoto app's context menu. Several of/// these could be used in a GridView for a similar effect.////// When opened, the child animates to show its full aspect ratio and has/// rounded corners. The larger size of the open CupertinoContextMenu allows/// the FittedBox to fit the entire image, even when it has a very tall or/// wide aspect ratio compared to the square of a GridView, so this animates/// into view as the CupertinoContextMenu is opened. The preview is swapped in/// right when the open animation begins, which includes the rounded corners.////// ```dart/// CupertinoContextMenu(/// // The FittedBox in the preview here allows the image to animate its/// // aspect ratio when the CupertinoContextMenu is animating its preview/// // widget open and closed./// // ignore: deprecated_member_use/// previewBuilder: (BuildContext context, Animation<double> animation, Widget child) {/// return FittedBox(/// fit: BoxFit.cover,/// // This ClipRRect rounds the corners of the image when the/// // CupertinoContextMenu is open, even though it's not rounded when/// // it's closed. It uses the given animation to animate the corners/// // in sync with the opening animation./// child: ClipRRect(/// borderRadius: BorderRadius.circular(64.0 * animation.value),/// child: Image.asset('assets/photo.jpg'),/// ),/// );/// },/// actions: <Widget>[/// CupertinoContextMenuAction(/// child: const Text('Action one'),/// onPressed: () {},/// ),/// ],/// child: FittedBox(/// fit: BoxFit.cover,/// child: Image.asset('assets/photo.jpg'),/// ),/// )/// ```////// {@end-tool}@Deprecated('Use CupertinoContextMenu.builder instead. ''This feature was deprecated after v3.4.0-34.1.pre.',)final ContextMenuPreviewBuilder? previewBuilder;@overrideState<CupertinoContextMenu> createState() => _CupertinoContextMenuState();}4 unmodified lines// Animates the child while it's opening.late AnimationController _openController;Rect? _decoyChildEndRect;OverlayEntry? _lastOverlayEntry;_ContextMenuRoute<void>? _route;final double _midpoint = CupertinoContextMenu.animationOpensAt / 2;8 unmodified linesupperBound: CupertinoContextMenu.animationOpensAt,);_openController.addStatusListener(_onDecoyAnimationStatusChange);_tapGestureRecognizer = TapGestureRecognizer()..onTapCancel = _onTapCancel..onTapDown = _onTapDown..onTapUp = _onTapUp..onTap = _onTap;}void _listenerCallback() {if (_openController.status != AnimationStatus.reverse &&_openController.value >= _midpoint) {if (widget.enableHapticFeedback) {HapticFeedback.heavyImpact();}15 unmodified linesfinal double screenWidth = MediaQuery.sizeOf(context).width;final double center = screenWidth / 2;final bool centerDividesChild = childRect.left < center&& childRect.right > center;final double distanceFromCenter = (center - childRect.center.dx).abs();if (centerDividesChild && distanceFromCenter <= childRect.width / 4) {return _ContextMenuLocation.center;6 unmodified linesreturn _ContextMenuLocation.left;}// Push the new route and open the CupertinoContextMenu overlay.void _openContextMenu() {setState(() {3 unmodified lines_route = _ContextMenuRoute<void>(actions: widget.actions,barrierLabel: CupertinoLocalizations.of(context).menuDismissLabel,filter: ui.ImageFilter.blur(sigmaX: 5.0,sigmaY: 5.0,),contextMenuLocation: _contextMenuLocation,previousChildRect: _decoyChildEndRect!,builder: (BuildContext context, Animation<double> animation) {if (widget.child == null) {final Animation<double> localAnimation = Tween<double>(begin: CupertinoContextMenu.animationOpensAt, end: 1).animate(animation);return widget.builder(context, localAnimation);}return widget.previewBuilder!(context, animation, widget.child!);},);Navigator.of(context, rootNavigator: true).push<void>(_route!);37 unmodified lines// Watch for when _ContextMenuRoute is closed and return to the state where// the CupertinoContextMenu just behaves as a Container.void _routeAnimationStatusListener(AnimationStatus status) {if (status != AnimationStatus.dismissed) {return;}if (mounted) {33 unmodified lines});final Rect childRect = _getRect(_childGlobalKey);_decoyChildEndRect = Rect.fromCenter(center: childRect.center,width: childRect.width * _kOpenScale,height: childRect.height * _kOpenScale,);// Create a decoy child in an overlay directly on top of the original child.74 unmodified linesclass _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin {late Animation<Rect?> _rect;late Animation<Decoration> _boxDecoration;@overridevoid initState() {3 unmodified linesconst double openAnimationLength = 5.0;const double totalOpenAnimationLength = beginPause + openAnimationLength;final double endPause =((totalOpenAnimationLength * _animationDuration) / _previewLongPressTimeout.inMilliseconds) - totalOpenAnimationLength;// The timing on the animation was eyeballed from the XCode iOS simulator// running iOS 16.0.// Because the animation no longer goes from 0.0 to 1.0, but to a number// depending on the ratio between the press animation time and the opening26 unmodified lines),]).animate(widget.controller);_boxDecoration = DecorationTween(begin: const BoxDecoration(color: Color(0xFFFFFFFF),boxShadow: <BoxShadow>[],),end: const BoxDecoration(color: Color(0xFFFFFFFF),boxShadow: _endBoxShadow,),).animate(CurvedAnimation(parent: widget.controller,curve: Interval(0.0, CupertinoContextMenu.animationOpensAt),),);}Widget _buildAnimation(BuildContext context, Widget? child) {return Positioned.fromRect(rect: _rect.value!,child: Container(decoration: _boxDecoration.value,child: widget.child,),);}4 unmodified lines);}@overrideWidget build(BuildContext context) {return Stack(17 unmodified linesCupertinoContextMenuBuilder? builder,super.filter,required Rect previousChildRect,super.settings,}) : assert(actions.isNotEmpty),_actions = actions,_builder = builder,_contextMenuLocation = contextMenuLocation,_previousChildRect = previousChildRect;// Barrier color for a Cupertino modal barrier.static const Color _kModalBarrierColor = Color(0x6604040F);4 unmodified linesfinal _ContextMenuLocation _contextMenuLocation;bool _externalOffstage = false;bool _internalOffstage = false;Orientation? _lastOrientation;// The Rect of the child at the moment that the CupertinoContextMenu opens.final Rect _previousChildRect;double? _scale = 1.0;final GlobalKey _sheetGlobalKey = GlobalKey();static final CurveTween _curve = CurveTween(curve: Curves.easeOutBack,);static final CurveTween _curveReverse = CurveTween(curve: Curves.easeInBack,);static final RectTween _rectTween = RectTween();static final Animatable<Rect?> _rectAnimatable = _rectTween.chain(_curve);static final RectTween _rectTweenReverse = RectTween();static final Animatable<Rect?> _rectAnimatableReverse = _rectTweenReverse.chain(_curveReverse,);static final RectTween _sheetRectTween = RectTween();final Animatable<Rect?> _sheetRectAnimatable = _sheetRectTween.chain(_curve,);final Animatable<Rect?> _sheetRectAnimatableReverse = _sheetRectTween.chain(_curveReverse,);static final Tween<double> _sheetScaleTween = Tween<double>();static final Animatable<double> _sheetScaleAnimatable = _sheetScaleTween.chain(_curve,);static final Animatable<double> _sheetScaleAnimatableReverse =_sheetScaleTween.chain(_curveReverse,);final Tween<double> _opacityTween = Tween<double>(begin: 0.0, end: 1.0);late Animation<double> _sheetOpacity;12 unmodified lines@overrideDuration get transitionDuration => _kModalPopupTransitionDuration;// Getting the RenderBox doesn't include the scale from the Transform.scale,// so it's manually accounted for here.static Rect _getScaledRect(GlobalKey globalKey, double scale) {9 unmodified lines// Get the alignment for the _ContextMenuSheet's Transform.scale based on the// contextMenuLocation.static AlignmentDirectional getSheetAlignment(_ContextMenuLocation contextMenuLocation) {switch (contextMenuLocation) {case _ContextMenuLocation.center:return AlignmentDirectional.topCenter;case _ContextMenuLocation.right:return AlignmentDirectional.topEnd;case _ContextMenuLocation.left:return AlignmentDirectional.topStart;}}// The place to start the sheetRect animation from.static Rect _getSheetRectBegin(Orientation? orientation, _ContextMenuLocation contextMenuLocation, Rect childRect, Rect sheetRect) {switch (contextMenuLocation) {case _ContextMenuLocation.center:final Offset target = orientation == Orientation.portrait? childRect.bottomCenter: childRect.topCenter;final Offset centered = target - Offset(sheetRect.width / 2, 0.0);return centered & sheetRect.size;case _ContextMenuLocation.right:final Offset target = orientation == Orientation.portrait? childRect.bottomRight: childRect.topRight;return (target - Offset(sheetRect.width, 0.0)) & sheetRect.size;case _ContextMenuLocation.left:final Offset target = orientation == Orientation.portrait? childRect.bottomLeft: childRect.topLeft;return target & sheetRect.size;}}1 unmodified linevoid _onDismiss(BuildContext context, double scale, double opacity) {_scale = scale;_opacityTween.end = opacity;_sheetOpacity = _opacityTween.animate(CurvedAnimation(parent: animation!,curve: const Interval(0.9, 1.0),));Navigator.of(context).pop();}// Take measurements on the child and _ContextMenuSheet and update the// animation tweens to match.void _updateTweenRects() {final Rect childRect = _scale == null? _getRect(_childGlobalKey): _getScaledRect(_childGlobalKey, _scale!);_rectTween.begin = _previousChildRect;_rectTween.end = childRect;2 unmodified lines// to the original position before the bounce.final Rect childRectOriginal = Rect.fromCenter(center: _previousChildRect.center,width: _previousChildRect.width / _kOpenScale,height: _previousChildRect.height / _kOpenScale,);final Rect sheetRect = _getRect(_sheetGlobalKey);49 unmodified lines@overrideAnimation<double> createAnimation() {final Animation<double> animation = super.createAnimation();_sheetOpacity = _opacityTween.animate(CurvedAnimation(parent: animation,curve: Curves.linear,));return animation;}@overrideWidget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {// This is usually used to build the "page", which is then passed to// buildTransitions as child, the idea being that buildTransitions will// animate the entire page into the scene. In the case of _ContextMenuRoute,3 unmodified lines}@overrideWidget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {return OrientationBuilder(builder: (BuildContext context, Orientation orientation) {_lastOrientation = orientation;2 unmodified lines// they're movable.if (!animation.isCompleted) {final bool reverse = animation.status == AnimationStatus.reverse;final Rect rect = reverse? _rectAnimatableReverse.evaluate(animation)!: _rectAnimatable.evaluate(animation)!;final Rect sheetRect = reverse? _sheetRectAnimatableReverse.evaluate(animation)!: _sheetRectAnimatable.evaluate(animation)!;final double sheetScale = reverse? _sheetScaleAnimatableReverse.evaluate(animation): _sheetScaleAnimatable.evaluate(animation);return Stack(children: <Widget>[Positioned.fromRect(35 unmodified lines},);}}// The final state of the _ContextMenuRoute after animating in and before21 unmodified lines_ContextMenuRouteStaticState createState() => _ContextMenuRouteStaticState();}class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with TickerProviderStateMixin {// The child is scaled down as it is dragged down until it hits this minimum// value.static const double _kMinScale = 0.8;5 unmodified lineslate Offset _dragOffset;double _lastScale = 1.0;late AnimationController _moveController;late AnimationController _sheetController;late Animation<Offset> _moveAnimation;late Animation<double> _sheetScaleAnimation;late Animation<double> _sheetOpacityAnimation;1 unmodified line// The scale of the child changes as a function of the distance it is dragged.static double _getScale(Orientation orientation, double maxDragDistance, double dy) {final double dyDirectional = dy <= 0.0 ? dy : -dy;return math.max(_kMinScale,(maxDragDistance + dyDirectional) / maxDragDistance,);}void _onPanStart(DragStartDetails details) {9 unmodified lines// If flung, animate a bit before handling the potential dismiss.if (details.velocity.pixelsPerSecond.dy.abs() >= kMinFlingVelocity) {final bool flingIsAway = details.velocity.pixelsPerSecond.dy > 0;final double finalPosition = flingIsAway? _moveAnimation.value.dy + 100.0: 0.0;if (flingIsAway && _sheetController.status != AnimationStatus.forward) {_sheetController.forward();6 unmodified linesend: Offset(0.0, finalPosition),).animate(_moveController);_moveController.reset();_moveController.duration = const Duration(milliseconds: 64,);_moveController.forward();_moveController.addStatusListener(_flingStatusListener);return;14 unmodified lines// When the scale passes the threshold, animate the sheet back in.if (_lastScale > _kSheetScaleThreshold) {_moveController.removeListener(_moveListener);if (_sheetController.status != AnimationStatus.dismissed) {_sheetController.reverse();}}}void _flingStatusListener(AnimationStatus status) {if (status != AnimationStatus.completed) {return;}10 unmodified lines}Alignment _getChildAlignment(Orientation orientation, _ContextMenuLocation contextMenuLocation) {switch (contextMenuLocation) {case _ContextMenuLocation.center:return orientation == Orientation.portrait? Alignment.bottomCenter: Alignment.topRight;case _ContextMenuLocation.right:return orientation == Orientation.portrait? Alignment.bottomCenter: Alignment.topLeft;case _ContextMenuLocation.left:return orientation == Orientation.portrait? Alignment.bottomCenter: Alignment.topRight;}}void _setDragOffset(Offset dragOffset) {// Allow horizontal and negative vertical movement, but damp it.final double endX = _kPadding * dragOffset.dx / _kDamping;final double endY = dragOffset.dy >= 0.0? dragOffset.dy: _kPadding * dragOffset.dy / _kDamping;setState(() {_dragOffset = dragOffset;_moveAnimation = Tween<Offset>(begin: Offset.zero,end: Offset(clampDouble(endX, -_kPadding, _kPadding),endY,),).animate(CurvedAnimation(parent: _moveController,curve: Curves.elasticIn,),);// Fade the _ContextMenuSheet out or in, if needed.if (_lastScale <= _kSheetScaleThreshold&& _sheetController.status != AnimationStatus.forward&& _sheetScaleAnimation.value != 0.0) {_sheetController.forward();} else if (_lastScale > _kSheetScaleThreshold&& _sheetController.status != AnimationStatus.reverse&& _sheetScaleAnimation.value != 1.0) {_sheetController.reverse();}});5 unmodified linesList<Widget> _getChildren(Orientation orientation, _ContextMenuLocation contextMenuLocation) {final Expanded child = Expanded(child: Align(alignment: _getChildAlignment(widget.orientation,widget.contextMenuLocation,),child: AnimatedBuilder(animation: _moveController,builder: _buildChildAnimation,1 unmodified line),),);const SizedBox spacer = SizedBox(width: _kPadding,height: _kPadding,);final Expanded sheet = Expanded(child: AnimatedBuilder(animation: _sheetController,7 unmodified lines),);switch (contextMenuLocation) {case _ContextMenuLocation.center:return <Widget>[child, spacer, sheet];case _ContextMenuLocation.right:return orientation == Orientation.portrait? <Widget>[child, spacer, sheet]: <Widget>[sheet, spacer, child];case _ContextMenuLocation.left:return <Widget>[child, spacer, sheet];}}// Build the animation for the _ContextMenuSheet.1 unmodified linereturn Transform.scale(alignment: _ContextMenuRoute.getSheetAlignment(widget.contextMenuLocation),scale: _sheetScaleAnimation.value,child: FadeTransition(opacity: _sheetOpacityAnimation,child: child,),);}4 unmodified linesMediaQuery.sizeOf(context).height,_moveAnimation.value.dy,);return Transform.scale(key: widget.childGlobalKey,scale: _lastScale,child: child,);}// Build the animation for the overall draggable dismissible content.Widget _buildAnimation(BuildContext context, Widget? child) {return Transform.translate(offset: _moveAnimation.value,child: child,);}@override4 unmodified linesvalue: 1.0,vsync: this,);_sheetController = AnimationController(duration: const Duration(milliseconds: 100),reverseDuration: const Duration(milliseconds: 300),vsync: this,);_sheetScaleAnimation = Tween<double>(begin: 1.0,end: 0.0,).animate(CurvedAnimation(parent: _sheetController,curve: Curves.linear,reverseCurve: Curves.easeInBack,),);_sheetOpacityAnimation = Tween<double>(begin: 1.0,end: 0.0,).animate(_sheetController);_setDragOffset(Offset.zero);}@overridevoid dispose() {_moveController.dispose();_sheetController.dispose();super.dispose();}@overrideWidget build(BuildContext context) {final List<Widget> children = _getChildren(widget.orientation,widget.contextMenuLocation,);return SafeArea(child: Align(5 unmodified lineschild: AnimatedBuilder(animation: _moveController,builder: _buildAnimation,child: widget.orientation == Orientation.portrait? Column(crossAxisAlignment: CrossAxisAlignment.start,children: children,): Row(crossAxisAlignment: CrossAxisAlignment.start,children: children,),),),),3 unmodified lines// The menu that displays when CupertinoContextMenu is open. It consists of a// list of actions that are typically CupertinoContextMenuActions.class _ContextMenuSheet extends StatelessWidget {_ContextMenuSheet({super.key,required this.actions,required _ContextMenuLocation contextMenuLocation,required Orientation orientation,}) : assert(actions.isNotEmpty),_contextMenuLocation = contextMenuLocation,_orientation = orientation;final List<Widget> actions;final _ContextMenuLocation _contextMenuLocation;final Orientation _orientation;static const double _kMenuWidth = 250.0;// Get the children, whose order depends on orientation and// contextMenuLocation.3 unmodified lineschild: IntrinsicHeight(child: ClipRRect(borderRadius: const BorderRadius.all(Radius.circular(13.0)),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: <Widget>[actions.first,for (final Widget action in actions.skip(1))DecoratedBox(decoration: BoxDecoration(border: Border(top: BorderSide(color: CupertinoDynamicColor.resolve(_borderColor,context,),width: 0.4,),),),position: DecorationPosition.foreground,child: action,),],),),),);switch (_contextMenuLocation) {case _ContextMenuLocation.center:return _orientation == Orientation.portrait? <Widget>[const Spacer(),menu,const Spacer(),]: <Widget>[menu,const Spacer(),];case _ContextMenuLocation.right:return <Widget>[const Spacer(),menu,];case _ContextMenuLocation.left:return <Widget>[menu,const Spacer(),];}}@overrideWidget build(BuildContext context) {return Row(crossAxisAlignment: CrossAxisAlignment.start,children: getChildren(context),);}}1 unmodified line23456789105 unmodified lines16171819202122232425262728293031323334351 unmodified line37383940414243444546474849505152531 unmodified line555657585960616263646566676869707172737475767778798081828384858687888990919293941 unmodified line9697989910010120 unmodified lines1221231241251261279 unmodified lines13713813914014114214327 unmodified lines17117217317417517617717817944 unmodified lines22422522622722822923023123223346 unmodified lines28028128228328428528628728842 unmodified lines33133233333433533633733833934034134234334414 unmodified lines3593603613623633644 unmodified lines3693703713723733743758 unmodified lines38438538638738838939039139239339439539639739839915 unmodified lines4154164174184194204216 unmodified lines4284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644653 unmodified lines46947047147247347447547647747847948048148248348448548648737 unmodified lines52552652752852953053133 unmodified lines56556656756856957057157257357457557657774 unmodified lines6526536546556566576583 unmodified lines66266366466566666766866967067167226 unmodified lines6997007017027037047057067077087097107117127137147157167177184 unmodified lines72372472572672772872973073173273373417 unmodified lines7527537547557567577587597607617627637647654 unmodified lines77077177277377477577677777877978078178278378478578678778878979079179279379479579612 unmodified lines8098108118128138148158168178189 unmodified lines8288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598601 unmodified line8628638648658668678688698708718728738748758768778788798802 unmodified lines88388488588688788888989049 unmodified lines9409419429439449459469479489499509519529539549559569579589593 unmodified lines9639649659669679689699709719729739742 unmodified lines97797897998098198298398498598698798898999099199299399435 unmodified lines103010311032103310341035103610371038103910401041104221 unmodified lines106410651066106710681069107010715 unmodified lines10771078107910801081108210831084108510861 unmodified line10881089109010911092109310949 unmodified lines11041105110611071108110911106 unmodified lines111711181119112011211122112314 unmodified lines1138113911401141114211431144114511461147114811491150115110 unmodified lines1162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611975 unmodified lines12031204120512061207120812091 unmodified line12111212121312141215121612177 unmodified lines12251226122712281229123012311232123312341235123612371238123912401 unmodified line12421243124412451246124712484 unmodified lines1253125412551256125712581259126012611262126312644 unmodified lines12691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113025 unmodified lines130813091310131113121313131413151316131713181319132013213 unmodified lines1325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913603 unmodified lines136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'context_menu_action.dart';library;import 'dart:math' as math;import 'dart:ui' as ui;5 unmodified linesimport 'colors.dart';import 'localizations.dart';import 'scrollbar.dart';// The scale of the child at the time that the CupertinoContextMenu opens.// This value was eyeballed from a physical device running iOS 13.1.2.const double _kOpenScale = 1.15;// The smallest possible scale of the child, used if opening the// CupertinoContextMenu would cause it to go outside the safe area. This value// was eyeballed from the Xcode iPhone simulator running iOS 16.1.const double _kMinScaleFactor = 1.02;// The ratio for the borderRadius of the context menu preview image. This value// was eyeballed by overlapping the CupertinoContextMenu with a context menu// from iOS 16.0 in the Xcode iPhone simulator.const double _previewBorderRadiusRatio = 12.0;// The duration of the transition used when a modal popup is shown. Eyeballed1 unmodified lineconst Duration _kModalPopupTransitionDuration = Duration(milliseconds: 335);// The duration it takes for the CupertinoContextMenu to open.// This value was eyeballed from the Xcode simulator running iOS 16.0.const Duration _previewLongPressTimeout = Duration(milliseconds: 800);// The total length of the combined animations until the menu is fully open.final int _animationDuration =_previewLongPressTimeout.inMilliseconds + _kModalPopupTransitionDuration.inMilliseconds;// The final box shadow for the opening child widget.// This value was eyeballed from the Xcode simulator running iOS 16.0.const List<BoxShadow> _endBoxShadow = <BoxShadow>[BoxShadow(color: Color(0x40000000), blurRadius: 10.0, spreadRadius: 0.5),];const Color _borderColor = CupertinoDynamicColor.withBrightness(1 unmodified linedarkColor: Color(0xFF57585A),);const Color _kBackgroundColor = CupertinoDynamicColor.withBrightness(color: Color(0xFFF1F1F1),darkColor: Color(0xFF212122),);typedef _DismissCallback = void Function(BuildContext context, double scale, double opacity);/// A function that builds the child and handles the transition between the/// default child and the preview when the CupertinoContextMenu is open.typedef CupertinoContextMenuBuilder =Widget Function(BuildContext context, Animation<double> animation);// Given a GlobalKey, return the Rect of the corresponding RenderBox's// paintBounds in global coordinates.Rect _getRect(GlobalKey globalKey) {assert(globalKey.currentContext != null);final RenderBox renderBoxContainer = globalKey.currentContext!.findRenderObject()! as RenderBox;return Rect.fromPoints(renderBoxContainer.localToGlobal(renderBoxContainer.paintBounds.topLeft),renderBoxContainer.localToGlobal(renderBoxContainer.paintBounds.bottomRight),);}// The context menu arranges itself slightly differently based on the location// on the screen of [CupertinoContextMenu.child] before the// [CupertinoContextMenu] opens.enum _ContextMenuLocation { center, left, right }/// A full-screen modal route that opens when the [child] is long-pressed.////// When open, the [CupertinoContextMenu] shows the child in a large full-screen/// [Overlay] with a list of buttons specified by [actions]. The child/preview is/// placed in an [Expanded] widget so that it will grow to fill the Overlay if/// its size is unconstrained.////// When closed, the [CupertinoContextMenu] displays the child as if the/// [CupertinoContextMenu] were not there. Sizing and positioning is unaffected.1 unmodified line/// background or by calling `Navigator.pop(context)`. Unlike [PopupRoute], it can/// also be closed by swiping downwards.////// {@tool dartpad}/// This sample shows a very simple [CupertinoContextMenu] for the Flutter logo./// Long press on it to open.20 unmodified linesrequired this.actions,required Widget this.child,this.enableHapticFeedback = false,}) : assert(actions.isNotEmpty),builder = ((BuildContext context, Animation<double> animation) => child);9 unmodified linesrequired this.builder,this.enableHapticFeedback = false,}) : assert(actions.isNotEmpty),child = null;/// Exposes the default border radius for matching iOS 16.0 behavior. This/// value was eyeballed from the iOS simulator running iOS 16.0.27 unmodified lines////// final Animation<Decoration> boxDecorationAnimation = DecorationTween(/// begin: const BoxDecoration(/// boxShadow: <BoxShadow>[],/// ),/// end: const BoxDecoration(/// boxShadow: CupertinoContextMenu.kEndBoxShadow,/// ),/// ).animate(44 unmodified linesstatic final double animationOpensAt =_previewLongPressTimeout.inMilliseconds / _animationDuration;/// The background color of a [CupertinoContextMenuAction] and a/// [CupertinoContextMenu] sheet.static const Color kBackgroundColor = _kBackgroundColor;/// A function that returns a widget to be used alternatively from [child].////// The widget returned by the function will be shown at all times: when the46 unmodified lines////// final Animation<Decoration> boxDecorationAnimation = DecorationTween(/// begin: const BoxDecoration(/// boxShadow: <BoxShadow>[],/// ),/// end: const BoxDecoration(/// boxShadow: CupertinoContextMenu.kEndBoxShadow,/// ),/// ).animate(42 unmodified lines/// {@end-tool}final CupertinoContextMenuBuilder builder;// TODO(mitchgoodwin): deprecate [child] with builder refactor https://github.com/flutter/flutter/issues/116306/// The widget that can be "opened" with the [CupertinoContextMenu].////// When the [CupertinoContextMenu] is long-pressed, the menu will open and/// this widget will be moved to the new route and placed inside of an/// [Expanded] widget. This allows the child to resize to fit in its place in/// the new route, if it doesn't size itself.////// When the [CupertinoContextMenu] is "closed", this widget acts like a/// [Container], i.e. it does not constrain its child's size or affect its14 unmodified lines/// Defaults to false.final bool enableHapticFeedback;@overrideState<CupertinoContextMenu> createState() => _CupertinoContextMenuState();}4 unmodified lines// Animates the child while it's opening.late AnimationController _openController;Rect? _decoyChildEndRect;late double _scaleFactor;OverlayEntry? _lastOverlayEntry;_ContextMenuRoute<void>? _route;final double _midpoint = CupertinoContextMenu.animationOpensAt / 2;8 unmodified linesupperBound: CupertinoContextMenu.animationOpensAt,);_openController.addStatusListener(_onDecoyAnimationStatusChange);_tapGestureRecognizer =TapGestureRecognizer()..onTapCancel = _onTapCancel..onTapDown = _onTapDown..onTapUp = _onTapUp..onTap = _onTap;}void _listenerCallback() {if (_openController.status != AnimationStatus.reverse && _openController.value >= _midpoint) {if (widget.enableHapticFeedback) {HapticFeedback.heavyImpact();}15 unmodified linesfinal double screenWidth = MediaQuery.sizeOf(context).width;final double center = screenWidth / 2;final bool centerDividesChild = childRect.left < center && childRect.right > center;final double distanceFromCenter = (center - childRect.center.dx).abs();if (centerDividesChild && distanceFromCenter <= childRect.width / 4) {return _ContextMenuLocation.center;6 unmodified linesreturn _ContextMenuLocation.left;}// Constrain the size of the expanded child so that it does not go outside the// safe area. See https://github.com/flutter/flutter/issues/122951.static double _computeScaleFactor(Rect childRect, EdgeInsets padding, Size size) {final double leftMaxScale = 2 * (childRect.center.dx - padding.left) / childRect.width;final double topMaxScale = 2 * (childRect.center.dy - padding.top) / childRect.height;final double rightMaxScale =2 * (size.width - padding.right - childRect.center.dx) / childRect.width;final double bottomMaxScale =2 * (size.height - padding.bottom - childRect.center.dy) / childRect.height;final double minWidth = math.min(leftMaxScale, rightMaxScale);final double minHeight = math.min(topMaxScale, bottomMaxScale);// Return the smallest scale factor that keeps the child mostly onscreen.return clampDouble(math.min(minWidth, minHeight), _kMinScaleFactor, _kOpenScale);}/// The default preview builder if none is provided. It makes a rectangle/// around the child widget with rounded borders, matching the iOS 16 opened/// context menu eyeballed on the Xcode iOS simulator.static Widget _defaultPreviewBuilder(BuildContext context,Animation<double> animation,Widget child,) {return FittedBox(fit: BoxFit.cover,child: ClipRRect(borderRadius: BorderRadius.circular(_previewBorderRadiusRatio * animation.value),child: child,),);}// Push the new route and open the CupertinoContextMenu overlay.void _openContextMenu() {setState(() {3 unmodified lines_route = _ContextMenuRoute<void>(actions: widget.actions,barrierLabel: CupertinoLocalizations.of(context).menuDismissLabel,filter: ui.ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),contextMenuLocation: _contextMenuLocation,previousChildRect: _decoyChildEndRect!,scaleFactor: _scaleFactor,builder: (BuildContext context, Animation<double> animation) {if (widget.child == null) {final Animation<double> localAnimation = Tween<double>(begin: CupertinoContextMenu.animationOpensAt,end: 1,).animate(animation);return widget.builder(context, localAnimation);}return _defaultPreviewBuilder(context, animation, widget.child!);},);Navigator.of(context, rootNavigator: true).push<void>(_route!);37 unmodified lines// Watch for when _ContextMenuRoute is closed and return to the state where// the CupertinoContextMenu just behaves as a Container.void _routeAnimationStatusListener(AnimationStatus status) {if (!status.isDismissed) {return;}if (mounted) {33 unmodified lines});final Rect childRect = _getRect(_childGlobalKey);final EdgeInsets safeAreaPadding = MediaQuery.paddingOf(context);final Size screenSize = MediaQuery.sizeOf(context);_scaleFactor = _computeScaleFactor(childRect, safeAreaPadding, screenSize);_decoyChildEndRect = Rect.fromCenter(center: childRect.center,width: childRect.width * _scaleFactor,height: childRect.height * _scaleFactor,);// Create a decoy child in an overlay directly on top of the original child.74 unmodified linesclass _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin {late Animation<Rect?> _rect;late Animation<Decoration> _boxDecoration;late final CurvedAnimation _boxDecorationCurvedAnimation;@overridevoid initState() {3 unmodified linesconst double openAnimationLength = 5.0;const double totalOpenAnimationLength = beginPause + openAnimationLength;final double endPause =((totalOpenAnimationLength * _animationDuration) /_previewLongPressTimeout.inMilliseconds) -totalOpenAnimationLength;// The timing on the animation was eyeballed from the Xcode iOS simulator// running iOS 16.0.// Because the animation no longer goes from 0.0 to 1.0, but to a number// depending on the ratio between the press animation time and the opening26 unmodified lines),]).animate(widget.controller);_boxDecorationCurvedAnimation = CurvedAnimation(parent: widget.controller,curve: Interval(0.0, CupertinoContextMenu.animationOpensAt),);_boxDecoration = DecorationTween(begin: const BoxDecoration(boxShadow: <BoxShadow>[]),end: const BoxDecoration(boxShadow: _endBoxShadow),).animate(_boxDecorationCurvedAnimation);}Widget _buildAnimation(BuildContext context, Widget? child) {return Positioned.fromRect(rect: _rect.value!,child: Container(decoration: _boxDecoration.value, child: widget.child),);}4 unmodified lines);}@overridevoid dispose() {_boxDecorationCurvedAnimation.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return Stack(17 unmodified linesCupertinoContextMenuBuilder? builder,super.filter,required Rect previousChildRect,required double scaleFactor,super.settings,}) : assert(actions.isNotEmpty),_actions = actions,_builder = builder,_contextMenuLocation = contextMenuLocation,_previousChildRect = previousChildRect,_scaleFactor = scaleFactor;// Barrier color for a Cupertino modal barrier.static const Color _kModalBarrierColor = Color(0x6604040F);4 unmodified linesfinal _ContextMenuLocation _contextMenuLocation;bool _externalOffstage = false;bool _internalOffstage = false;final double _scaleFactor;Orientation? _lastOrientation;// The Rect of the child at the moment that the CupertinoContextMenu opens.final Rect _previousChildRect;double? _scale = 1.0;final GlobalKey _sheetGlobalKey = GlobalKey();static final CurveTween _curve = CurveTween(curve: Curves.easeOutBack);static final CurveTween _curveReverse = CurveTween(curve: Curves.easeInBack);static final RectTween _rectTween = RectTween();static final Animatable<Rect?> _rectAnimatable = _rectTween.chain(_curve);static final RectTween _rectTweenReverse = RectTween();static final Animatable<Rect?> _rectAnimatableReverse = _rectTweenReverse.chain(_curveReverse);static final RectTween _sheetRectTween = RectTween();final Animatable<Rect?> _sheetRectAnimatable = _sheetRectTween.chain(_curve);final Animatable<Rect?> _sheetRectAnimatableReverse = _sheetRectTween.chain(_curveReverse);static final Tween<double> _sheetScaleTween = Tween<double>();static final Animatable<double> _sheetScaleAnimatable = _sheetScaleTween.chain(_curve);static final Animatable<double> _sheetScaleAnimatableReverse = _sheetScaleTween.chain(_curveReverse,);final Tween<double> _opacityTween = Tween<double>(begin: 0.0, end: 1.0);late Animation<double> _sheetOpacity;12 unmodified lines@overrideDuration get transitionDuration => _kModalPopupTransitionDuration;CurvedAnimation? _curvedAnimation;CurvedAnimation? _sheetOpacityCurvedAnimation;// Getting the RenderBox doesn't include the scale from the Transform.scale,// so it's manually accounted for here.static Rect _getScaledRect(GlobalKey globalKey, double scale) {9 unmodified lines// Get the alignment for the _ContextMenuSheet's Transform.scale based on the// contextMenuLocation.static AlignmentDirectional getSheetAlignment(_ContextMenuLocation contextMenuLocation) {return switch (contextMenuLocation) {_ContextMenuLocation.center => AlignmentDirectional.topCenter,_ContextMenuLocation.right => AlignmentDirectional.topEnd,_ContextMenuLocation.left => AlignmentDirectional.topStart,};}// The place to start the sheetRect animation from.static Rect _getSheetRectBegin(Orientation? orientation,_ContextMenuLocation contextMenuLocation,Rect childRect,Rect sheetRect,) {switch (contextMenuLocation) {case _ContextMenuLocation.center:final Offset target =orientation == Orientation.portrait ? childRect.bottomCenter : childRect.topCenter;final Offset centered = target - Offset(sheetRect.width / 2, 0.0);return centered & sheetRect.size;case _ContextMenuLocation.right:final Offset target =orientation == Orientation.portrait ? childRect.bottomRight : childRect.topRight;return (target - Offset(sheetRect.width, 0.0)) & sheetRect.size;case _ContextMenuLocation.left:final Offset target =orientation == Orientation.portrait ? childRect.bottomLeft : childRect.topLeft;return target & sheetRect.size;}}1 unmodified linevoid _onDismiss(BuildContext context, double scale, double opacity) {_scale = scale;_opacityTween.end = opacity;_sheetOpacityCurvedAnimation = CurvedAnimation(parent: animation!,curve: const Interval(0.9, 1.0),);_sheetOpacity = _opacityTween.animate(_sheetOpacityCurvedAnimation!);Navigator.of(context).pop();}// Take measurements on the child and _ContextMenuSheet and update the// animation tweens to match.void _updateTweenRects() {final Rect childRect =_scale == null ? _getRect(_childGlobalKey) : _getScaledRect(_childGlobalKey, _scale!);_rectTween.begin = _previousChildRect;_rectTween.end = childRect;2 unmodified lines// to the original position before the bounce.final Rect childRectOriginal = Rect.fromCenter(center: _previousChildRect.center,width: _previousChildRect.width / _scaleFactor,height: _previousChildRect.height / _scaleFactor,);final Rect sheetRect = _getRect(_sheetGlobalKey);49 unmodified lines@overrideAnimation<double> createAnimation() {final Animation<double> animation = super.createAnimation();if (_curvedAnimation?.parent != animation) {_curvedAnimation?.dispose();_curvedAnimation = CurvedAnimation(parent: animation, curve: Curves.linear);}_sheetOpacity = _opacityTween.animate(_curvedAnimation!);return animation;}@overrideWidget buildPage(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,) {// This is usually used to build the "page", which is then passed to// buildTransitions as child, the idea being that buildTransitions will// animate the entire page into the scene. In the case of _ContextMenuRoute,3 unmodified lines}@overrideWidget buildTransitions(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,Widget child,) {return OrientationBuilder(builder: (BuildContext context, Orientation orientation) {_lastOrientation = orientation;2 unmodified lines// they're movable.if (!animation.isCompleted) {final bool reverse = animation.status == AnimationStatus.reverse;final Rect rect =reverse? _rectAnimatableReverse.evaluate(animation)!: _rectAnimatable.evaluate(animation)!;final Rect sheetRect =reverse? _sheetRectAnimatableReverse.evaluate(animation)!: _sheetRectAnimatable.evaluate(animation)!;final double sheetScale =reverse? _sheetScaleAnimatableReverse.evaluate(animation): _sheetScaleAnimatable.evaluate(animation);return Stack(children: <Widget>[Positioned.fromRect(35 unmodified lines},);}@overridevoid dispose() {_curvedAnimation?.dispose();_sheetOpacityCurvedAnimation?.dispose();super.dispose();}}// The final state of the _ContextMenuRoute after animating in and before21 unmodified lines_ContextMenuRouteStaticState createState() => _ContextMenuRouteStaticState();}class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic>with TickerProviderStateMixin {// The child is scaled down as it is dragged down until it hits this minimum// value.static const double _kMinScale = 0.8;5 unmodified lineslate Offset _dragOffset;double _lastScale = 1.0;late final AnimationController _moveController;late final CurvedAnimation _moveCurvedAnimation;late final AnimationController _sheetController;late final CurvedAnimation _sheetCurvedAnimation;late Animation<Offset> _moveAnimation;late Animation<double> _sheetScaleAnimation;late Animation<double> _sheetOpacityAnimation;1 unmodified line// The scale of the child changes as a function of the distance it is dragged.static double _getScale(Orientation orientation, double maxDragDistance, double dy) {final double dyDirectional = dy <= 0.0 ? dy : -dy;return math.max(_kMinScale, (maxDragDistance + dyDirectional) / maxDragDistance);}void _onPanStart(DragStartDetails details) {9 unmodified lines// If flung, animate a bit before handling the potential dismiss.if (details.velocity.pixelsPerSecond.dy.abs() >= kMinFlingVelocity) {final bool flingIsAway = details.velocity.pixelsPerSecond.dy > 0;final double finalPosition = flingIsAway ? _moveAnimation.value.dy + 100.0 : 0.0;if (flingIsAway && _sheetController.status != AnimationStatus.forward) {_sheetController.forward();6 unmodified linesend: Offset(0.0, finalPosition),).animate(_moveController);_moveController.reset();_moveController.duration = const Duration(milliseconds: 64);_moveController.forward();_moveController.addStatusListener(_flingStatusListener);return;14 unmodified lines// When the scale passes the threshold, animate the sheet back in.if (_lastScale > _kSheetScaleThreshold) {_moveController.removeListener(_moveListener);if (!_sheetController.isDismissed) {_sheetController.reverse();}}}void _flingStatusListener(AnimationStatus status) {if (!status.isCompleted) {return;}10 unmodified lines}Alignment _getChildAlignment(Orientation orientation, _ContextMenuLocation contextMenuLocation) {if (orientation == Orientation.portrait) {return Alignment.bottomCenter;}return switch (contextMenuLocation) {_ContextMenuLocation.left => Alignment.topRight,_ContextMenuLocation.center => Alignment.topRight,_ContextMenuLocation.right => Alignment.topLeft,};}void _setDragOffset(Offset dragOffset) {// Allow horizontal and negative vertical movement, but damp it.final double endX = _kPadding * dragOffset.dx / _kDamping;final double endY =dragOffset.dy >= 0.0 ? dragOffset.dy : _kPadding * dragOffset.dy / _kDamping;setState(() {_dragOffset = dragOffset;_moveAnimation = Tween<Offset>(begin: Offset.zero,end: Offset(clampDouble(endX, -_kPadding, _kPadding), endY),).animate(_moveCurvedAnimation);// Fade the _ContextMenuSheet out or in, if needed.if (_lastScale <= _kSheetScaleThreshold &&_sheetController.status != AnimationStatus.forward &&_sheetScaleAnimation.value != 0.0) {_sheetController.forward();} else if (_lastScale > _kSheetScaleThreshold &&_sheetController.status != AnimationStatus.reverse &&_sheetScaleAnimation.value != 1.0) {_sheetController.reverse();}});5 unmodified linesList<Widget> _getChildren(Orientation orientation, _ContextMenuLocation contextMenuLocation) {final Expanded child = Expanded(child: Align(alignment: _getChildAlignment(widget.orientation, widget.contextMenuLocation),child: AnimatedBuilder(animation: _moveController,builder: _buildChildAnimation,1 unmodified line),),);const SizedBox spacer = SizedBox(width: _kPadding, height: _kPadding);final Expanded sheet = Expanded(child: AnimatedBuilder(animation: _sheetController,7 unmodified lines),);return switch (contextMenuLocation) {_ContextMenuLocation.right when orientation == Orientation.portrait => <Widget>[child,spacer,sheet,],_ContextMenuLocation.right => <Widget>[sheet, spacer, child],_ContextMenuLocation.center => <Widget>[child, spacer, sheet],_ContextMenuLocation.left => <Widget>[child, spacer, sheet],};}// Build the animation for the _ContextMenuSheet.1 unmodified linereturn Transform.scale(alignment: _ContextMenuRoute.getSheetAlignment(widget.contextMenuLocation),scale: _sheetScaleAnimation.value,child: FadeTransition(opacity: _sheetOpacityAnimation, child: child),);}4 unmodified linesMediaQuery.sizeOf(context).height,_moveAnimation.value.dy,);return Transform.scale(key: widget.childGlobalKey, scale: _lastScale, child: child);}// Build the animation for the overall draggable dismissible content.Widget _buildAnimation(BuildContext context, Widget? child) {return Transform.translate(offset: _moveAnimation.value, child: child);}@override4 unmodified linesvalue: 1.0,vsync: this,);_moveCurvedAnimation = CurvedAnimation(parent: _moveController, curve: Curves.elasticIn);_sheetController = AnimationController(duration: const Duration(milliseconds: 100),reverseDuration: const Duration(milliseconds: 300),vsync: this,);_sheetCurvedAnimation = CurvedAnimation(parent: _sheetController,curve: Curves.linear,reverseCurve: Curves.easeInBack,);_sheetScaleAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(_sheetCurvedAnimation);_sheetOpacityAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(_sheetController);_setDragOffset(Offset.zero);}@overridevoid dispose() {_moveController.dispose();_moveCurvedAnimation.dispose();_sheetController.dispose();_sheetCurvedAnimation.dispose();super.dispose();}@overrideWidget build(BuildContext context) {final List<Widget> children = _getChildren(widget.orientation, widget.contextMenuLocation);return SafeArea(child: Align(5 unmodified lineschild: AnimatedBuilder(animation: _moveController,builder: _buildAnimation,child: Flex(direction: switch (widget.orientation) {Orientation.portrait => Axis.vertical,Orientation.landscape => Axis.horizontal,},crossAxisAlignment: CrossAxisAlignment.start,children: children,),),),),3 unmodified lines// The menu that displays when CupertinoContextMenu is open. It consists of a// list of actions that are typically CupertinoContextMenuActions.class _ContextMenuSheet extends StatefulWidget {_ContextMenuSheet({super.key,required this.actions,required this.contextMenuLocation,required this.orientation,}) : assert(actions.isNotEmpty);final List<Widget> actions;final _ContextMenuLocation contextMenuLocation;final Orientation orientation;@overrideState<_ContextMenuSheet> createState() => _ContextMenuSheetState();}class _ContextMenuSheetState extends State<_ContextMenuSheet> {late final ScrollController _controller;static const double _kMenuWidth = 250.0;// Eyeballed on a context menu on an iOS 15 simulator running iOS 17.5.static const double _kScrollbarMainAxisMargin = 13.0;@overridevoid initState() {super.initState();// Link the scrollbar to the scroll view by providing both the same scroll// controller. Using SingleChildScrollview.primary might conflict with users// already using the PrimaryScrollController._controller = ScrollController();}// Get the children, whose order depends on orientation and// contextMenuLocation.3 unmodified lineschild: IntrinsicHeight(child: ClipRRect(borderRadius: const BorderRadius.all(Radius.circular(13.0)),child: ColoredBox(color: CupertinoDynamicColor.resolve(CupertinoContextMenu.kBackgroundColor, context),child: ScrollConfiguration(behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),child: CupertinoScrollbar(mainAxisMargin: _kScrollbarMainAxisMargin,controller: _controller,child: SingleChildScrollView(controller: _controller,child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: <Widget>[widget.actions.first,for (final Widget action in widget.actions.skip(1))DecoratedBox(decoration: BoxDecoration(border: Border(top: BorderSide(color: CupertinoDynamicColor.resolve(_borderColor, context),width: 0.4,),),),position: DecorationPosition.foreground,child: action,),],),),),),),),),);return switch (widget.contextMenuLocation) {_ContextMenuLocation.center when widget.orientation == Orientation.portrait => <Widget>[const Spacer(),menu,const Spacer(),],_ContextMenuLocation.center => <Widget>[menu, const Spacer()],_ContextMenuLocation.right => <Widget>[const Spacer(), menu],_ContextMenuLocation.left => <Widget>[menu, const Spacer()],};}@overridevoid dispose() {_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return Row(crossAxisAlignment: CrossAxisAlignment.start, children: getChildren(context));}}
4 unmodified lines567891036 unmodified lines4748495051525354555632 unmodified lines89909192939495969798991001011021031049 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501514 unmodified linesimport 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';/// A button in a _ContextMenuSheet.///36 unmodified lines}class _CupertinoContextMenuActionState extends State<CupertinoContextMenuAction> {static const Color _kBackgroundColor = CupertinoDynamicColor.withBrightness(color: Color(0xFFF1F1F1),darkColor: Color(0xFF212122),);static const Color _kBackgroundColorPressed = CupertinoDynamicColor.withBrightness(color: Color(0xFFDDDDDD),darkColor: Color(0xFF3F3F40),32 unmodified linesTextStyle get _textStyle {if (widget.isDefaultAction) {return _kActionSheetActionStyle.copyWith(fontWeight: FontWeight.w600,);}if (widget.isDestructiveAction) {return _kActionSheetActionStyle.copyWith(color: CupertinoColors.destructiveRed,);}return _kActionSheetActionStyle.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.label, context));}9 unmodified linesonTap: widget.onPressed,behavior: HitTestBehavior.opaque,child: ConstrainedBox(constraints: const BoxConstraints(minHeight: _kButtonHeight,),child: Semantics(button: true,child: Container(decoration: BoxDecoration(color: _isPressed? CupertinoDynamicColor.resolve(_kBackgroundColorPressed, context): CupertinoDynamicColor.resolve(_kBackgroundColor, context),),padding: const EdgeInsets.only(top: 8,bottom: 8,left: 15.5,right: 17.5,),child: DefaultTextStyle(style: _textStyle,child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[Flexible(child: widget.child,),if (widget.trailingIcon != null)Icon(widget.trailingIcon,color: _textStyle.color,size: 21.0,),],),),),4 unmodified lines56789101136 unmodified lines48495051525332 unmodified lines86878889909192939495969798991009 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371384 unmodified linesimport 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'context_menu.dart';/// A button in a _ContextMenuSheet.///36 unmodified lines}class _CupertinoContextMenuActionState extends State<CupertinoContextMenuAction> {static const Color _kBackgroundColorPressed = CupertinoDynamicColor.withBrightness(color: Color(0xFFDDDDDD),darkColor: Color(0xFF3F3F40),32 unmodified linesTextStyle get _textStyle {if (widget.isDefaultAction) {return _kActionSheetActionStyle.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.label, context),fontWeight: FontWeight.w600,);}if (widget.isDestructiveAction) {return _kActionSheetActionStyle.copyWith(color: CupertinoColors.destructiveRed);}return _kActionSheetActionStyle.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.label, context),);}9 unmodified linesonTap: widget.onPressed,behavior: HitTestBehavior.opaque,child: ConstrainedBox(constraints: const BoxConstraints(minHeight: _kButtonHeight),child: Semantics(button: true,child: ColoredBox(color:_isPressed? CupertinoDynamicColor.resolve(_kBackgroundColorPressed, context): CupertinoDynamicColor.resolve(CupertinoContextMenu.kBackgroundColor,context,),child: Padding(padding: const EdgeInsets.fromLTRB(15.5, 8.0, 17.5, 8.0),child: DefaultTextStyle(style: _textStyle,child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[Flexible(child: widget.child),if (widget.trailingIcon != null)Icon(widget.trailingIcon, color: _textStyle.color, size: 21.0),],),),),),
1 unmodified line23456711 unmodified lines19202122232425262728293031323317 unmodified lines51525354555657585960615 unmodified lines67686970717273747562 unmodified lines13813914014114214314414511 unmodified lines1571581591601611621631641651661671681 unmodified line17017117217317417518 unmodified lines19419519619719819990 unmodified lines29029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333470 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334 unmodified lines43843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851922 unmodified lines54254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457529 unmodified lines60560660760860961061161261361413 unmodified lines62862963063163263363463563663763863964017 unmodified lines65865966066166266366466566666718 unmodified lines68668768868969069169269369469513 unmodified lines7097107117127137147157163 unmodified lines72072172272372472572639 unmodified lines76676776876977077177277377477577677777877914 unmodified lines79479579679779879980080180280380458 unmodified lines86386486586686786886927 unmodified lines8978988999009019029039048 unmodified lines91391491591691791891924 unmodified lines9449459469479489499509512 unmodified lines95495595695795895996096196296315 unmodified lines97998098198298398498598698798898999099199299399499599699799820 unmodified lines1019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110112 unmodified lines111411151116111711181119112011211122112371 unmodified lines119511961197119811991200120112021203120412051206120712081209121024 unmodified lines1235123612371238123912401241124212431244124512461 unmodified line124812491250125112521253125423 unmodified lines1278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130012 unmodified lines1313131413151316131713189 unmodified lines1328132913301331133213331334133523 unmodified lines135913601361136213631364136543 unmodified lines1409141014111412141314141415141629 unmodified lines14461447144814491450145114521 unmodified line1454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149112 unmodified lines15041505150615071508150915101511151265 unmodified lines15781579158015811582158315841585158615871588158923 unmodified lines1613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163527 unmodified lines1663166416651666166716681669167011 unmodified lines16821683168416851686168716885 unmodified lines16941695169616971698169917002 unmodified lines170317041705170617071708170923 unmodified lines1733173417351736173717381739174015 unmodified lines175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180726 unmodified lines18341835183618371838183918405 unmodified lines184618471848184918501851185218531854185551 unmodified lines190719081909191019111912191319141915191619171918191919201921192227 unmodified lines1950195119521953195419551 unmodified line1957195819591960196119621963196419651966196719681969197094 unmodified lines20652066206720682069207020712072207320742 unmodified lines20772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210323 unmodified lines21272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321544 unmodified lines21592160216121622163216421652166216721682169217021712172217321742175217621772178217921805 unmodified lines218621872188218921902191219221932194219521962197219821992200220122022203220422054 unmodified lines22102211221222132214221522163 unmodified lines22202221222222232224222522266 unmodified lines22332234223522362237223822391 unmodified line2241224222432244224522462247224815 unmodified lines226422652266226722682269227022712272227322742275227622772278227922802281228222833 unmodified lines22872288228922902291229222936 unmodified lines23002301230223032304230523061 unmodified line230823092310231123122313231423153 unmodified lines231923202321232223232324232523262327232823291 unmodified line233123322333233423352336233723382339234023412342234323442345234623472348234923503 unmodified lines235423552356235723582359236022 unmodified lines2383238423852386238723882389239022 unmodified lines241324142415241624172418241924201 unmodified line24222423242424252426242724287 unmodified lines2436243724382439244024412442244324442445244624472448244924502451245224532454245510 unmodified lines2466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125221 unmodified line2524252525262527252825292530253125322533253425352536253725382539254025411 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;import 'package:flutter/scheduler.dart';11 unmodified linesconst double _kPickerWidth = 320.0;const double _kPickerHeight = 216.0;const bool _kUseMagnifier = true;const double _kMagnification = 2.35/2.1;const double _kDatePickerPadSize = 12.0;// The density of a date picker is different from a generic picker.// Eyeballed from iOS.const double _kSqueeze = 1.25;const TextStyle _kDefaultPickerTextStyle = TextStyle(letterSpacing: -0.83,);// The item height is 32 and the magnifier height is 34, from// iOS simulators with "Debug View Hierarchy".17 unmodified lines// The width of each column of the countdown time picker.const double _kTimerPickerColumnIntrinsicWidth = 106;TextStyle _themeTextStyle(BuildContext context, { bool isValid = true }) {final TextStyle style = CupertinoTheme.of(context).textTheme.dateTimePickerTextStyle;return isValid? style.copyWith(color: CupertinoDynamicColor.maybeResolve(style.color, context)): style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context));}void _animateColumnControllerToItem(FixedExtentScrollController controller, int targetItem) {5 unmodified lines}const Widget _startSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capEndEdge: false);const Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false, capEndEdge: false);const Widget _endSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false);// 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.62 unmodified lines@overridebool shouldRelayout(_DatePickerLayoutDelegate oldDelegate) {return columnWidths != oldDelegate.columnWidths|| textDirectionFactor != oldDelegate.textDirectionFactor;}}11 unmodified lines////// Example: ` 4 | 14 | PM `.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.////// Example: ` July | 13 | 2012 `.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.1 unmodified line////// Example: ` Fri Jul 13 | 4 | 14 | PM `dateAndTime,/// Mode that shows the date in month and year./// Name of month is spelled in full./// Column order is subject to internationalization.18 unmodified linesminute,// AM/PM column in time and dateAndTime mode.dayPeriod,}/// A date picker widget in iOS style.90 unmodified linesthis.dateOrder,this.backgroundColor,this.showDayOfWeek = false,this.itemExtent = _kItemExtent,}) : initialDateTime = initialDateTime ?? DateTime.now(),assert(itemExtent > 0,'item extent should be greater than 0',),assert(minuteInterval > 0 && 60 % minuteInterval == 0,'minute interval is not a positive integer factor of 60',) {assert(mode != CupertinoDatePickerMode.dateAndTime || minimumDate == null || !this.initialDateTime.isBefore(minimumDate!),'initial date is before minimum date',);assert(mode != CupertinoDatePickerMode.dateAndTime || maximumDate == null || !this.initialDateTime.isAfter(maximumDate!),'initial date is after maximum date',);assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) || (minimumYear >= 1 && this.initialDateTime.year >= minimumYear),'initial year is not greater than minimum year, or minimum year is not positive',);assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) || maximumYear == null || this.initialDateTime.year <= maximumYear!,'initial year is not smaller than maximum year',);assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) || minimumDate == null || !minimumDate!.isAfter(this.initialDateTime),'initial date ${this.initialDateTime} is not greater than or equal to minimumDate $minimumDate',);assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) || maximumDate == null || !maximumDate!.isBefore(this.initialDateTime),'initial date ${this.initialDateTime} is not less than or equal to maximumDate $maximumDate',);assert(this.initialDateTime.minute % minuteInterval == 0,'initial minute is not divisible by minute interval',);}/// The mode of the date picker as one of [CupertinoDatePickerMode]. Defaults/// to [CupertinoDatePickerMode.dateAndTime]. Value cannot change after70 unmodified lines/// Defaults to null, which disables background painting entirely.final Color? backgroundColor;/// Whether to to show day of week alongside day. Defaults to false.final bool showDayOfWeek;/// {@macro flutter.cupertino.picker.itemExtent}////// Defaults to a value that matches the default iOS date picker wheel.final double itemExtent;@overrideState<StatefulWidget> createState() { // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499// 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.switch (mode) {case CupertinoDatePickerMode.time:case CupertinoDatePickerMode.dateAndTime:return _CupertinoDatePickerDateTimeState();case CupertinoDatePickerMode.date:return _CupertinoDatePickerDateState(dateOrder: dateOrder);case CupertinoDatePickerMode.monthYear:return _CupertinoDatePickerMonthYearState(dateOrder: dateOrder);}}// Estimate the minimum width that each column needs to layout its content.4 unmodified linesbool showDayOfWeek, {bool standaloneMonth = false,}) {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;}}case _PickerColumnType.hour:for (int i = 0; i < 24; i++) {final String hour = localizations.datePickerHour(i);if (longestText.length < hour.length) {longestText = hour;}}case _PickerColumnType.minute:for (int i = 0; i < 60; i++) {final String minute = localizations.datePickerMinute(i);if (longestText.length < minute.length) {longestText = minute;}}case _PickerColumnType.dayPeriod:longestText =localizations.anteMeridiemAbbreviation.length > localizations.postMeridiemAbbreviation.length? localizations.anteMeridiemAbbreviation: localizations.postMeridiemAbbreviation;case _PickerColumnType.dayOfMonth:int longestDayOfMonth = 1;for (int i = 1; i <=31; i++) {final String dayOfMonth = localizations.datePickerDayOfMonth(i);if (longestText.length < dayOfMonth.length) {longestText = dayOfMonth;longestDayOfMonth = i;}}if (showDayOfWeek) {for (int wd = 1; wd < DateTime.daysPerWeek; wd++) {final String dayOfMonth = localizations.datePickerDayOfMonth(longestDayOfMonth, wd);if (longestText.length < dayOfMonth.length) {longestText = dayOfMonth;}}}case _PickerColumnType.month:for (int i = 1; i <= 12; i++) {final String month = standaloneMonth? localizations.datePickerStandaloneMonth(i): localizations.datePickerMonth(i);if (longestText.length < month.length) {longestText = month;}}case _PickerColumnType.year:longestText = localizations.datePickerYear(2018);}assert(longestText != '', 'column type is not appropriate');return TextPainter.computeMaxIntrinsicWidth(text: TextSpan(style: _themeTextStyle(context),text: longestText,),textDirection: Directionality.of(context),);}}typedef _ColumnBuilder = Widget Function(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay);class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {// Fraction of the farthest column's vanishing point vs its width. Eyeballed22 unmodified linesreturn 0;case CupertinoDatePickerMode.date:case CupertinoDatePickerMode.monthYear:break;}assert(false,'$runtimeType is only meant for dateAndTime mode or time mode',);return 0;}// The controller of the date column.late FixedExtentScrollController dateController;// 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.late FixedExtentScrollController hourController;// The current selection of the minute picker. Values range from 0 to 59.int get selectedMinute {return minuteController.hasClients? minuteController.selectedItem * widget.minuteInterval % 60: initialDateTime.minute;}// The controller of the minute column.late FixedExtentScrollController minuteController;29 unmodified linesbool isMeridiemPickerScrolling = false;bool get isScrolling {return isDatePickerScrolling|| isHourPickerScrolling|| isMinutePickerScrolling|| isMeridiemPickerScrolling;}// The estimated width of columns.13 unmodified linesmeridiemController = FixedExtentScrollController(initialItem: selectedAmPm);hourController = FixedExtentScrollController(initialItem: initialDateTime.hour);minuteController = FixedExtentScrollController(initialItem: initialDateTime.minute ~/ widget.minuteInterval);dateController = FixedExtentScrollController();PaintingBinding.instance.systemFonts.addListener(_handleSystemFontsChange);}void _handleSystemFontsChange () {setState(() {// System fonts change might cause the text layout width to change.// Clears cached width to ensure that they get recalculated with the17 unmodified linesvoid didUpdateWidget(CupertinoDatePicker oldWidget) {super.didUpdateWidget(oldWidget);assert(oldWidget.mode == widget.mode,"The $runtimeType's mode cannot change once it's built.",);if (!widget.use24hFormat && oldWidget.use24hFormat) {// Thanks to the physical and meridiem region mapping, the only thing we18 unmodified lines// 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, widget.showDayOfWeek);}return estimatedColumnWidths[columnType.index]!;}13 unmodified linesvoid _onSelectedItemChange(int index) {final DateTime selected = selectedDateTime;final bool isDateInvalid = (widget.minimumDate?.isAfter(selected) ?? false)|| (widget.maximumDate?.isBefore(selected) ?? false);if (isDateInvalid) {return;3 unmodified lines}// Builds the date column. The date is displayed in medium date format (e.g. Fri Aug 31).Widget _buildMediumDatePicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {39 unmodified linesreturn 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)),);},selectionOverlay: selectionOverlay,),14 unmodified lines// 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);}Widget _buildHourPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {58 unmodified lines);}Widget _buildMinutePicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {27 unmodified linesminute,);final bool isInvalidMinute = (widget.minimumDate?.isAfter(date) ?? false)|| (widget.maximumDate?.isBefore(date) ?? false);return itemPositioningBuilder(context,8 unmodified lines);}Widget _buildAmPmPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {24 unmodified linescontext,Text(index == 0? localizations.anteMeridiemAbbreviation: localizations.postMeridiemAbbreviation,style: _themeTextStyle(context, isValid: _isValidHour(index, _selectedHourIndex)),),);2 unmodified lines);}// 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;15 unmodified linesvoid _scrollToDate(DateTime newDate, DateTime fromDate, bool minCheck) {SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {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(20 unmodified lines];// 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];// 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));} else {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));} else {pickerBuilders.insert(0, _buildMediumDatePicker);columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));}}final List<Widget> pickers = <Widget>[];double totalColumnWidths = 4 * _kDatePickerPadSize;for (int i = 0; i < columnWidths.length; i++) {double offAxisFraction = 0.0;Widget selectionOverlay = _centerSelectionOverlay;if (i == 0) {offAxisFraction = -_kMaximumOffAxisFraction * textDirectionFactor;selectionOverlay = _startSelectionOverlay;} else if (i >= 2 || columnWidths.length == 2) {offAxisFraction = _kMaximumOffAxisFraction * textDirectionFactor;}EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);if (i == columnWidths.length - 1) {padding = padding.flipped;selectionOverlay = _endSelectionOverlay;}if (textDirectionFactor == -1) {padding = padding.flipped;}totalColumnWidths += columnWidths[i] + (2 * _kDatePickerPadSize);pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction,(BuildContext context, Widget? child) {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,),);},selectionOverlay,),));}final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(12 unmodified lines}class _CupertinoDatePickerDateState extends State<CupertinoDatePicker> {_CupertinoDatePickerDateState({required this.dateOrder,});final DatePickerDateOrder? dateOrder;71 unmodified lines}void _refreshEstimatedColumnWidths() {estimatedColumnWidths[_PickerColumnType.dayOfMonth.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.dayOfMonth, localizations, context, widget.showDayOfWeek);estimatedColumnWidths[_PickerColumnType.month.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.month, localizations, context, widget.showDayOfWeek);estimatedColumnWidths[_PickerColumnType.year.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.year, localizations, context, widget.showDayOfWeek);}// 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);Widget _buildDayPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {final int daysInCurrentMonth = _lastDayInMonth(selectedYear, selectedMonth).day;return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {24 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(31, (int index) {final int day = index + 1;final int? dayOfWeek = widget.showDayOfWeek ? DateTime(selectedYear, selectedMonth, day).weekday : null;return itemPositioningBuilder(context,Text(localizations.datePickerDayOfMonth(day, dayOfWeek),style: _themeTextStyle(context, isValid: day <= daysInCurrentMonth),),);}),1 unmodified line);}Widget _buildMonthPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {23 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(12, (int index) {final int month = index + 1;final bool isInvalidMonth = (widget.minimumDate?.year == selectedYear && widget.minimumDate!.month > month)|| (widget.maximumDate?.year == selectedYear && widget.maximumDate!.month < month);final String monthName = (widget.mode == CupertinoDatePickerMode.monthYear) ? localizations.datePickerStandaloneMonth(month) : localizations.datePickerMonth(month);return itemPositioningBuilder(context,Text(monthName,style: _themeTextStyle(context, isValid: !isInvalidMonth),),);}),),);}Widget _buildYearPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {12 unmodified linesuseMagnifier: _kUseMagnifier,magnification: _kMagnification,backgroundColor: widget.backgroundColor,onSelectedItemChanged: (int index) {selectedYear = index;if (_isCurrentDateValid) {9 unmodified linesreturn null;}final bool isValidYear = (widget.minimumDate == null || widget.minimumDate!.year <= year)&& (widget.maximumDate == null || widget.maximumDate!.year >= year);return itemPositioningBuilder(context,23 unmodified linesvoid _pickerDidStopScrolling() {// Call setState to update the greyed out days/months/years, as the currently// selected year/month may have changed.setState(() { });if (isScrolling) {return;43 unmodified linesList<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[];List<double> columnWidths = <double>[];final DatePickerDateOrder datePickerDateOrder =dateOrder ?? localizations.datePickerDateOrder;switch (datePickerDateOrder) {case DatePickerDateOrder.mdy:29 unmodified linesfinal List<Widget> pickers = <Widget>[];double totalColumnWidths = 4 * _kDatePickerPadSize;for (int i = 0; i < columnWidths.length; i++) {final double offAxisFraction = (i - 1) * 0.3 * textDirectionFactor;EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);1 unmodified linepadding = const EdgeInsets.only(left: _kDatePickerPadSize);}Widget selectionOverlay = _centerSelectionOverlay;if (i == 0) {selectionOverlay = _startSelectionOverlay;} else if (i == columnWidths.length - 1) {selectionOverlay = _endSelectionOverlay;}totalColumnWidths += columnWidths[i] + (2 * _kDatePickerPadSize);pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction,(BuildContext context, Widget? child) {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,),);},selectionOverlay,),));}final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(12 unmodified lines}class _CupertinoDatePickerMonthYearState extends State<CupertinoDatePicker> {_CupertinoDatePickerMonthYearState({required this.dateOrder,});final DatePickerDateOrder? dateOrder;65 unmodified lines}void _refreshEstimatedColumnWidths() {estimatedColumnWidths[_PickerColumnType.month.index] =CupertinoDatePicker._getColumnWidth(_PickerColumnType.month, localizations, context, false, standaloneMonth: widget.mode == CupertinoDatePickerMode.monthYear);estimatedColumnWidths[_PickerColumnType.year.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.year, localizations, context, false);}Widget _buildMonthPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {23 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(12, (int index) {final int month = index + 1;final bool isInvalidMonth = (widget.minimumDate?.year == selectedYear && widget.minimumDate!.month > month)|| (widget.maximumDate?.year == selectedYear && widget.maximumDate!.month < month);final String monthName = (widget.mode == CupertinoDatePickerMode.monthYear) ? localizations.datePickerStandaloneMonth(month) : localizations.datePickerMonth(month);return itemPositioningBuilder(context,Text(monthName,style: _themeTextStyle(context, isValid: !isInvalidMonth),),);}),),);}Widget _buildYearPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {27 unmodified linesreturn null;}final bool isValidYear = (widget.minimumDate == null || widget.minimumDate!.year <= year)&& (widget.maximumDate == null || widget.maximumDate!.year >= year);return itemPositioningBuilder(context,11 unmodified linesbool get _isCurrentDateValid {// The current date selection represents a range [minSelectedData, maxSelectDate].final DateTime minSelectedDate = DateTime(selectedYear, selectedMonth);final DateTime maxSelectedDate = DateTime(selectedYear, selectedMonth, widget.initialDateTime.day + 1);final bool minCheck = widget.minimumDate?.isBefore(maxSelectedDate) ?? true;final bool maxCheck = widget.maximumDate?.isBefore(minSelectedDate) ?? false;5 unmodified linesvoid _pickerDidStopScrolling() {// Call setState to update the greyed out days/months/years, as the currently// selected year/month may have changed.setState(() { });if (isScrolling) {return;2 unmodified lines// Whenever scrolling lands on an invalid entry, the picker// automatically scrolls to a valid one.final DateTime minSelectDate = DateTime(selectedYear, selectedMonth);final DateTime maxSelectDate = DateTime(selectedYear, selectedMonth, widget.initialDateTime.day + 1);final bool minCheck = widget.minimumDate?.isBefore(maxSelectDate) ?? true;final bool maxCheck = widget.maximumDate?.isBefore(minSelectDate) ?? false;23 unmodified linesList<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[];List<double> columnWidths = <double>[];final DatePickerDateOrder datePickerDateOrder =dateOrder ?? localizations.datePickerDateOrder;switch (datePickerDateOrder) {case DatePickerDateOrder.mdy:15 unmodified linesfinal List<Widget> pickers = <Widget>[];double totalColumnWidths = 3 * _kDatePickerPadSize;for (int i = 0; i < columnWidths.length; i++) {late final double offAxisFraction;switch (i) {case 0:offAxisFraction = -0.3 * textDirectionFactor;default:offAxisFraction = 0.5 * textDirectionFactor;}EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);if (textDirectionFactor == -1) {padding = const EdgeInsets.only(left: _kDatePickerPadSize);}Widget selectionOverlay = _centerSelectionOverlay;if (i == 0) {selectionOverlay = _startSelectionOverlay;} else if (i == columnWidths.length - 1) {selectionOverlay = _endSelectionOverlay;}totalColumnWidths += columnWidths[i] + (2 * _kDatePickerPadSize);pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction,(BuildContext context, Widget? child) {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,),);},selectionOverlay,),));}final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(26 unmodified lines// If the maximum width given to the picker is smaller than 320.0, the picker's// layout will be broken./// Different modes of [CupertinoTimerPicker].////// See also:5 unmodified lines////// Examples: 16 hours | 14 min.hm,/// Mode that shows the timer duration in minute and second.////// Examples: 14 min | 43 sec.ms,/// Mode that shows the timer duration in hour, minute, and second.////// Examples: 16 hours | 14 min | 43 sec.51 unmodified linesthis.backgroundColor,this.itemExtent = _kItemExtent,required this.onTimerDurationChanged,}) : assert(initialTimerDuration >= Duration.zero),assert(initialTimerDuration < const Duration(days: 1)),assert(minuteInterval > 0 && 60 % minuteInterval == 0),assert(secondInterval > 0 && 60 % secondInterval == 0),assert(initialTimerDuration.inMinutes % minuteInterval == 0),assert(initialTimerDuration.inSeconds % secondInterval == 0),assert(itemExtent > 0,'item extent should be greater than 0');/// The mode of the timer picker.final CupertinoTimerPickerMode mode;27 unmodified lines/// Defaults to a value that matches the default iOS timer picker wheel.final double itemExtent;@overrideState<StatefulWidget> createState() => _CupertinoTimerPickerState();}1 unmodified lineclass _CupertinoTimerPickerState extends State<CupertinoTimerPicker> {late TextDirection textDirection;late CupertinoLocalizations localizations;int get textDirectionFactor {switch (textDirection) {case TextDirection.ltr:return 1;case TextDirection.rtl:return -1;}}// The currently selected values of the picker.int? selectedHour;94 unmodified lines// - If two different 1-digit numbers are of the same width, their corresponding// 2 digit numbers are of the same width.for (final String input in numbers) {textPainter.text = TextSpan(text: input,style: textStyle,);textPainter.layout();if (textPainter.maxIntrinsicWidth > maxWidth) {2 unmodified lines}}textPainter.text = TextSpan(text: '$widestNumber$widestNumber',style: textStyle,);textPainter.layout();numberLabelWidth = textPainter.maxIntrinsicWidth;numberLabelHeight = textPainter.height;numberLabelBaseline = textPainter.computeDistanceToActualBaseline(TextBaseline.alphabetic);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);}}23 unmodified lines// 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,fontWeight: FontWeight.w600,),maxLines: 1,softWrap: false,),),),4 unmodified lines// 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),),);}Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {_hourScrollController ??= FixedExtentScrollController(initialItem: selectedHour!);return CupertinoPicker(scrollController: _hourScrollController,magnification: _kMagnification,5 unmodified linessetState(() {selectedHour = index;widget.onTimerDurationChanged(Duration(hours: selectedHour!,minutes: selectedMinute,seconds: selectedSecond ?? 0,),);});},selectionOverlay: selectionOverlay,children: List<Widget>.generate(24, (int index) {final String label = localizations.timerPickerHourLabel(index) ?? '';final String semanticsLabel = textDirectionFactor == 1? localizations.timerPickerHour(index) + label: label + localizations.timerPickerHour(index);return Semantics(label: semanticsLabel,4 unmodified lines);}Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() { lastSelectedHour = selectedHour; });return false;},child: _buildHourPicker(additionalPadding, selectionOverlay),6 unmodified lines);}Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {_minuteScrollController ??= FixedExtentScrollController(initialItem: selectedMinute ~/ widget.minuteInterval,);1 unmodified linescrollController: _minuteScrollController,magnification: _kMagnification,offAxisFraction: _calculateOffAxisFraction(additionalPadding.start,widget.mode == CupertinoTimerPickerMode.ms ? 0 : 1,),itemExtent: widget.itemExtent,backgroundColor: widget.backgroundColor,15 unmodified lineschildren: List<Widget>.generate(60 ~/ widget.minuteInterval, (int index) {final int minute = index * widget.minuteInterval;final String label = localizations.timerPickerMinuteLabel(minute) ?? '';final String semanticsLabel = textDirectionFactor == 1? localizations.timerPickerMinute(minute) + label: label + localizations.timerPickerMinute(minute);return Semantics(label: semanticsLabel,excludeSemantics: true,child: _buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding),);}),);}Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() { lastSelectedMinute = selectedMinute; });return false;},child: _buildMinutePicker(additionalPadding, selectionOverlay),6 unmodified lines);}Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {_secondScrollController ??= FixedExtentScrollController(initialItem: selectedSecond! ~/ widget.secondInterval,);1 unmodified linescrollController: _secondScrollController,magnification: _kMagnification,offAxisFraction: _calculateOffAxisFraction(additionalPadding.start,widget.mode == CupertinoTimerPickerMode.ms ? 1 : 2,),itemExtent: widget.itemExtent,backgroundColor: widget.backgroundColor,3 unmodified linessetState(() {selectedSecond = index * widget.secondInterval;widget.onTimerDurationChanged(Duration(hours: selectedHour ?? 0,minutes: selectedMinute,seconds: selectedSecond!,),);});},1 unmodified linechildren: List<Widget>.generate(60 ~/ widget.secondInterval, (int index) {final int second = index * widget.secondInterval;final String label = localizations.timerPickerSecondLabel(second) ?? '';final String semanticsLabel = textDirectionFactor == 1? localizations.timerPickerSecond(second) + label: label + localizations.timerPickerSecond(second);return Semantics(label: semanticsLabel,excludeSemantics: true,child: _buildPickerNumberLabel(localizations.timerPickerSecond(second), additionalPadding),);}),);}Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() { lastSelectedSecond = selectedSecond; });return false;},child: _buildSecondPicker(additionalPadding, selectionOverlay),22 unmodified linesfinal 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;22 unmodified linesif (constraints.maxWidth < totalWidth) {totalWidth = constraints.maxWidth;pickerColumnWidth =totalWidth / (widget.mode == CupertinoTimerPickerMode.hms ? 3 : 2);}final double baseLabelContentWidth = numberLabelWidth + _kTimerPickerLabelPadSize;1 unmodified lineswitch (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;7 unmodified linesminuteColumnEndPadding = _kTimerPickerMinHorizontalPadding;}columns = <Widget>[_buildHourColumn(EdgeInsetsDirectional.only(start: hourColumnStartPadding,end: pickerColumnWidth - hourColumnStartPadding - hourLabelContentWidth,),_startSelectionOverlay,),_buildMinuteColumn(EdgeInsetsDirectional.only(start: pickerColumnWidth - minuteColumnEndPadding - minuteLabelContentWidth,end: minuteColumnEndPadding,),_endSelectionOverlay,),];case CupertinoTimerPickerMode.ms:10 unmodified linesminuteColumnStartPadding = _kTimerPickerMinHorizontalPadding;}columns = <Widget>[_buildMinuteColumn(EdgeInsetsDirectional.only(start: minuteColumnStartPadding,end: pickerColumnWidth - minuteColumnStartPadding - minuteLabelContentWidth,),_startSelectionOverlay,),_buildSecondColumn(EdgeInsetsDirectional.only(start: pickerColumnWidth - secondColumnEndPadding - minuteLabelContentWidth,end: secondColumnEndPadding,),_endSelectionOverlay,),];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,end: math.max(hourColumnEndPadding, 0),),_startSelectionOverlay,),_buildMinuteColumn(EdgeInsetsDirectional.only(start: minuteColumnPadding,end: minuteColumnPadding,),_centerSelectionOverlay,),_buildSecondColumn(EdgeInsetsDirectional.only(start: math.max(secondColumnStartPadding, 0),end: _kTimerPickerMinHorizontalPadding,),_endSelectionOverlay,),];}final CupertinoThemeData themeData = CupertinoTheme.of(context);// The native iOS picker's text scaling is fixed, so we will also fix it// as well in our picker.return MediaQuery.withNoTextScaling(child: CupertinoTheme(data: themeData.copyWith(1 unmodified linepickerTextStyle: _textStyleFrom(context, _kTimerPickerMagnification),),),child: Align(alignment: widget.alignment,child: Container(color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context),width: totalWidth,height: _kPickerHeight,child: DefaultTextStyle(style: _textStyleFrom(context),child: Row(children: columns.map((Widget child) => Expanded(child: child)).toList(growable: false)),),),),),);},1 unmodified line23456789101111 unmodified lines2324252627282930313233343517 unmodified lines53545556575859606162635 unmodified lines697071727374757677787980818283848562 unmodified lines14814915015115215315415511 unmodified lines1671681691701711721731741751761771781791801 unmodified line18218318418518618718818 unmodified lines20720820921021121221321490 unmodified lines30530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736870 unmodified lines4394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185194 unmodified lines52452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261322 unmodified lines63663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967029 unmodified lines70070170270370470570670770870913 unmodified lines72372472572672772872973073173273373473573673717 unmodified lines75575675775875976076118 unmodified lines78078178278378478578678778878979079113 unmodified lines8058068078088098108118128133 unmodified lines81781881982082182282382482582682739 unmodified lines86786886987087187287387487587687787814 unmodified lines89389489589689789889990090190290390490590690758 unmodified lines96696796896997097197297397497597627 unmodified lines1004100510061007100810091010101110128 unmodified lines1021102210231024102510261027102810291030103124 unmodified lines105610571058105910601061106210632 unmodified lines10661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109815 unmodified lines1114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113620 unmodified lines11571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112 unmodified lines127412751276127712781279128071 unmodified lines1352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138624 unmodified lines1411141214131414141514161417141814191420142114221423142414251426142714281429143014311 unmodified line1433143414351436143714381439144014411442144323 unmodified lines146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149412 unmodified lines15071508150915101511151215139 unmodified lines15231524152515261527152815291530153123 unmodified lines155515561557155815591560156143 unmodified lines160516061607160816091610161129 unmodified lines164116421643164416451646164716481 unmodified line16501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169712 unmodified lines171017111712171317141715171665 unmodified lines1782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180723 unmodified lines183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185827 unmodified lines18861887188818891890189118921893189411 unmodified lines190619071908190919101911191219131914191519165 unmodified lines19221923192419251926192719282 unmodified lines1931193219331934193519361937193819391940194123 unmodified lines196519661967196819691970197115 unmodified lines198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204426 unmodified lines2071207220732074207520765 unmodified lines20822083208420852086208720882089209020912092209351 unmodified lines2145214621472148214921502151215221532154215521562157215827 unmodified lines21862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022311 unmodified line2233223422352236223722382239224022412242224394 unmodified lines23382339234023412342234323442 unmodified lines23472348234923502351235223532354235523562357235823592360236123622363236423652366236723 unmodified lines23912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724184 unmodified lines242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724485 unmodified lines245424552456245724582459246024612462246324642465246624672468246924704 unmodified lines24752476247724782479248024813 unmodified lines2485248624872488248924902491249224936 unmodified lines25002501250225032504250525061 unmodified line2508250925102511251225132514251515 unmodified lines2531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325543 unmodified lines2558255925602561256225632564256525666 unmodified lines25732574257525762577257825791 unmodified line258125822583258425852586258725883 unmodified lines25922593259425952596259725981 unmodified line2600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226233 unmodified lines26272628262926302631263226332634263522 unmodified lines265826592660266126622663266422 unmodified lines26872688268926902691269226931 unmodified line26952696269726982699270027017 unmodified lines27092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274410 unmodified lines27552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828691 unmodified line28712872287328742875287628771 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'route.dart';/// @docImport 'text_theme.dart';library;import 'dart:math' as math;import 'package:flutter/scheduler.dart';11 unmodified linesconst double _kPickerWidth = 320.0;const double _kPickerHeight = 216.0;const bool _kUseMagnifier = true;const double _kMagnification = 2.35 / 2.1;const double _kDatePickerPadSize = 12.0;// The density of a date picker is different from a generic picker.// Eyeballed from iOS.const double _kSqueeze = 1.25;const TextStyle _kDefaultPickerTextStyle = TextStyle(letterSpacing: -0.83);// The item height is 32 and the magnifier height is 34, from// iOS simulators with "Debug View Hierarchy".17 unmodified lines// The width of each column of the countdown time picker.const double _kTimerPickerColumnIntrinsicWidth = 106;TextStyle _themeTextStyle(BuildContext context, {bool isValid = true}) {final TextStyle style = CupertinoTheme.of(context).textTheme.dateTimePickerTextStyle;return isValid? style.copyWith(color: CupertinoDynamicColor.maybeResolve(style.color, context)): style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context));}void _animateColumnControllerToItem(FixedExtentScrollController controller, int targetItem) {5 unmodified lines}const Widget _startSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capEndEdge: false);const Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false,capEndEdge: false,);const Widget _endSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false);/// Defines a function signature for creating a widget that serves as a selection overlay,/// given the current context, the selected item's index, and the total number of columns.typedef SelectionOverlayBuilder =Widget? Function(BuildContext context, {required int columnCount, required int selectedIndex});// 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.62 unmodified lines@overridebool shouldRelayout(_DatePickerLayoutDelegate oldDelegate) {return columnWidths != oldDelegate.columnWidths ||textDirectionFactor != oldDelegate.textDirectionFactor;}}11 unmodified lines////// Example: ` 4 | 14 | PM `.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.////// Example: ` July | 13 | 2012 `.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.1 unmodified line////// Example: ` Fri Jul 13 | 4 | 14 | PM `dateAndTime,/// Mode that shows the date in month and year./// Name of month is spelled in full./// Column order is subject to internationalization.18 unmodified linesminute,// AM/PM column in time and dateAndTime mode.dayPeriod,// Time separator column in time and dateAndTime mode.timeSeparator,}/// A date picker widget in iOS style.90 unmodified linesthis.dateOrder,this.backgroundColor,this.showDayOfWeek = false,this.showTimeSeparator = false,this.itemExtent = _kItemExtent,this.selectionOverlayBuilder,}) : initialDateTime = initialDateTime ?? DateTime.now(),assert(itemExtent > 0, 'item extent should be greater than 0'),assert(minuteInterval > 0 && 60 % minuteInterval == 0,'minute interval is not a positive integer factor of 60',),assert(mode != CupertinoDatePickerMode.dateAndTime ||minimumDate == null ||!(initialDateTime ?? DateTime.now()).isBefore(minimumDate),'initial date is before minimum date',),assert(mode != CupertinoDatePickerMode.dateAndTime ||maximumDate == null ||!(initialDateTime ?? DateTime.now()).isAfter(maximumDate),'initial date is after maximum date',),assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) ||(minimumYear >= 1 && (initialDateTime ?? DateTime.now()).year >= minimumYear),'initial year is not greater than minimum year, or minimum year is not positive',),assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) ||maximumYear == null ||(initialDateTime ?? DateTime.now()).year <= maximumYear,'initial year is not smaller than maximum year',),assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) ||minimumDate == null ||!minimumDate.isAfter(initialDateTime ?? DateTime.now()),'initial date ${initialDateTime ?? DateTime.now()} is not greater than or equal to minimumDate $minimumDate',),assert((mode != CupertinoDatePickerMode.date && mode != CupertinoDatePickerMode.monthYear) ||maximumDate == null ||!maximumDate.isBefore(initialDateTime ?? DateTime.now()),'initial date ${initialDateTime ?? DateTime.now()} is not less than or equal to maximumDate $maximumDate',),assert((mode == CupertinoDatePickerMode.date) || !showDayOfWeek,'showDayOfWeek is only supported in date mode',),assert((initialDateTime ?? DateTime.now()).minute % minuteInterval == 0,'initial minute is not divisible by minute interval',),assert(!showTimeSeparator ||mode == CupertinoDatePickerMode.dateAndTime ||mode == CupertinoDatePickerMode.time,'showTimeSeparator is only supported in time or dateAndTime modes',);/// The mode of the date picker as one of [CupertinoDatePickerMode]. Defaults/// to [CupertinoDatePickerMode.dateAndTime]. Value cannot change after70 unmodified lines/// Defaults to null, which disables background painting entirely.final Color? backgroundColor;/// Whether to show the day of week alongside the day in [CupertinoDatePickerMode.date] mode.////// Defaults to false.final bool showDayOfWeek;/// Whether to show the time separator between hour and minute in the time/// [CupertinoDatePickerMode.time] and datetime [CupertinoDatePickerMode.dateAndTime]/// picker modes.////// Throws an error if set to true in [CupertinoDatePickerMode.date]/// and [CupertinoDatePickerMode.monthYear] mode.////// Defaults to false.final bool showTimeSeparator;/// {@macro flutter.cupertino.picker.itemExtent}////// Defaults to a value that matches the default iOS date picker wheel.final double itemExtent;/// A function that returns a widget that is overlaid on the picker/// to highlight the currently selected entry.////// If unspecified, it defaults to a [CupertinoPickerDefaultSelectionOverlay]/// which is a gray rounded rectangle overlay in iOS 14 style.////// If the selection overlay builder returns null, no overlay will be drawn.////// {@tool snippet}////// This example shows how to recreate the default selection overlay/// with selectionOverlayBuilder.////// ```dart/// CupertinoDatePicker(/// onDateTimeChanged: (DateTime newDateTime) {},/// mode: CupertinoDatePickerMode.date,/// initialDateTime: DateTime(2018, 9, 15),/// selectionOverlayBuilder: (/// BuildContext context, {/// required int selectedIndex,/// required int columnCount,/// }) {/// if (selectedIndex == 0) {/// return const CupertinoPickerDefaultSelectionOverlay(/// capEndEdge: false,/// );/// } else if (selectedIndex == columnCount - 1) {/// return const CupertinoPickerDefaultSelectionOverlay(/// capStartEdge: false,/// );/// }/// return const CupertinoPickerDefaultSelectionOverlay(/// capStartEdge: false,/// capEndEdge: false,/// );/// },/// )/// ```/// {@end-tool}final SelectionOverlayBuilder? selectionOverlayBuilder;@overrideState<StatefulWidget> createState() {// ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499return switch (mode) {// 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.CupertinoDatePickerMode.time => _CupertinoDatePickerDateTimeState(),CupertinoDatePickerMode.dateAndTime => _CupertinoDatePickerDateTimeState(),CupertinoDatePickerMode.date => _CupertinoDatePickerDateState(dateOrder: dateOrder),CupertinoDatePickerMode.monthYear => _CupertinoDatePickerMonthYearState(dateOrder: dateOrder),};}// Estimate the minimum width that each column needs to layout its content.4 unmodified linesbool showDayOfWeek, {bool standaloneMonth = false,}) {final List<String> longTexts = <String>[];switch (columnType) {case _PickerColumnType.date:for (int i = 1; i <= 12; i++) {final String date = localizations.datePickerMediumDate(DateTime(2018, i, 25));longTexts.add(date);}case _PickerColumnType.hour:for (int i = 0; i < 24; i++) {final String hour = localizations.datePickerHour(i);longTexts.add(hour);}case _PickerColumnType.minute:for (int i = 0; i < 60; i++) {final String minute = localizations.datePickerMinute(i);longTexts.add(minute);}case _PickerColumnType.dayPeriod:longTexts.add(localizations.anteMeridiemAbbreviation);longTexts.add(localizations.postMeridiemAbbreviation);case _PickerColumnType.dayOfMonth:int longestDayOfMonth = 1;for (int i = 1; i <= 31; i++) {final String dayOfMonth = localizations.datePickerDayOfMonth(i);longTexts.add(dayOfMonth);longestDayOfMonth = i;}if (showDayOfWeek) {for (int wd = 1; wd < DateTime.daysPerWeek; wd++) {final String dayOfMonth = localizations.datePickerDayOfMonth(longestDayOfMonth, wd);longTexts.add(dayOfMonth);}}case _PickerColumnType.month:for (int i = 1; i <= 12; i++) {final String month =standaloneMonth? localizations.datePickerStandaloneMonth(i): localizations.datePickerMonth(i);longTexts.add(month);}case _PickerColumnType.year:longTexts.add(localizations.datePickerYear(2018));case _PickerColumnType.timeSeparator:longTexts.add(':');}assert(longTexts.isNotEmpty && longTexts.every((String text) => text.isNotEmpty),'column type is not appropriate',);return getColumnWidth(texts: longTexts, context: context);}/// Returns the width of column in the picker.////// This method is intended for testing only. It calculates the width of the/// widest column in the picker based on the provided list of texts and the/// given [BuildContext].@visibleForTestingstatic double getColumnWidth({required List<String> texts,required BuildContext context,TextStyle? textStyle,}) {return texts.map((String text) => TextPainter.computeMaxIntrinsicWidth(text: TextSpan(style: textStyle ?? _themeTextStyle(context), text: text),textDirection: Directionality.of(context),),).reduce(math.max);}}typedef _ColumnBuilder =Widget Function(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,);class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {// Fraction of the farthest column's vanishing point vs its width. Eyeballed22 unmodified linesreturn 0;case CupertinoDatePickerMode.date:case CupertinoDatePickerMode.monthYear:break;}assert(false, '$runtimeType is only meant for dateAndTime mode or time mode');return 0;}// The controller of the date column.late FixedExtentScrollController dateController;// 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.late FixedExtentScrollController hourController;// The current selection of the minute picker. Values range from 0 to 59.int get selectedMinute {return minuteController.hasClients? minuteController.selectedItem * widget.minuteInterval % 60: initialDateTime.minute;}// The controller of the minute column.late FixedExtentScrollController minuteController;29 unmodified linesbool isMeridiemPickerScrolling = false;bool get isScrolling {return isDatePickerScrolling ||isHourPickerScrolling ||isMinutePickerScrolling ||isMeridiemPickerScrolling;}// The estimated width of columns.13 unmodified linesmeridiemController = FixedExtentScrollController(initialItem: selectedAmPm);hourController = FixedExtentScrollController(initialItem: initialDateTime.hour);minuteController = FixedExtentScrollController(initialItem: initialDateTime.minute ~/ widget.minuteInterval,);dateController = FixedExtentScrollController();PaintingBinding.instance.systemFonts.addListener(_handleSystemFontsChange);}void _handleSystemFontsChange() {setState(() {// System fonts change might cause the text layout width to change.// Clears cached width to ensure that they get recalculated with the17 unmodified linesvoid didUpdateWidget(CupertinoDatePicker oldWidget) {super.didUpdateWidget(oldWidget);assert(oldWidget.mode == widget.mode, "The $runtimeType's mode cannot change once it's built.");if (!widget.use24hFormat && oldWidget.use24hFormat) {// Thanks to the physical and meridiem region mapping, the only thing we18 unmodified lines// Lazily calculate the column width of the column being displayed only.double _getEstimatedColumnWidth(_PickerColumnType columnType) {estimatedColumnWidths[columnType.index] ??= CupertinoDatePicker._getColumnWidth(columnType,localizations,context,widget.showDayOfWeek,);return estimatedColumnWidths[columnType.index]!;}13 unmodified linesvoid _onSelectedItemChange(int index) {final DateTime selected = selectedDateTime;final bool isDateInvalid =(widget.minimumDate?.isAfter(selected) ?? false) ||(widget.maximumDate?.isBefore(selected) ?? false);if (isDateInvalid) {return;3 unmodified lines}// Builds the date column. The date is displayed in medium date format (e.g. Fri Aug 31).Widget _buildMediumDatePicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {39 unmodified linesreturn 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)));},selectionOverlay: selectionOverlay,),14 unmodified lines// 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);}Widget _buildHourPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {58 unmodified lines);}Widget _buildMinutePicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {27 unmodified linesminute,);final bool isInvalidMinute =(widget.minimumDate?.isAfter(date) ?? false) ||(widget.maximumDate?.isBefore(date) ?? false);return itemPositioningBuilder(context,8 unmodified lines);}Widget _buildAmPmPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {24 unmodified linescontext,Text(index == 0? localizations.anteMeridiemAbbreviation: localizations.postMeridiemAbbreviation,style: _themeTextStyle(context, isValid: _isValidHour(index, _selectedHourIndex)),),);2 unmodified lines);}// Builds the time separator column.Widget _buildTimeSeparatorWidget(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return ExcludeSemantics(child: CupertinoPicker(offAxisFraction: offAxisFraction,itemExtent: widget.itemExtent,useMagnifier: _kUseMagnifier,magnification: _kMagnification,backgroundColor: widget.backgroundColor,squeeze: _kSqueeze,onSelectedItemChanged: (int index) {},selectionOverlay: selectionOverlay,children: List<Widget>.generate(1, (int index) {return itemPositioningBuilder(context, Text(':', style: _themeTextStyle(context)));}),),);}// 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;15 unmodified linesvoid _scrollToDate(DateTime newDate, DateTime fromDate, bool minCheck) {SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {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(20 unmodified lines];// 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];// Adds time separator column if the picker is showing time separator.if (widget.showTimeSeparator) {columnWidths.insert(1, _getEstimatedColumnWidth(_PickerColumnType.timeSeparator));pickerBuilders.insert(1, _buildTimeSeparatorWidget);}// Adds am/pm column if the picker is not using 24h format.if (!widget.use24hFormat) {switch (localizations.datePickerDateTimeOrder) {case DatePickerDateTimeOrder.date_time_dayPeriod:case DatePickerDateTimeOrder.time_dayPeriod_date:pickerBuilders.add(_buildAmPmPicker);columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod));case DatePickerDateTimeOrder.date_dayPeriod_time:case DatePickerDateTimeOrder.dayPeriod_time_date: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) {switch (localizations.datePickerDateTimeOrder) {case DatePickerDateTimeOrder.time_dayPeriod_date:case DatePickerDateTimeOrder.dayPeriod_time_date:pickerBuilders.add(_buildMediumDatePicker);columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date));case DatePickerDateTimeOrder.date_time_dayPeriod:case DatePickerDateTimeOrder.date_dayPeriod_time:pickerBuilders.insert(0, _buildMediumDatePicker);columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));}}final List<Widget> pickers = <Widget>[];double totalColumnWidths = 4 * _kDatePickerPadSize;for (final (int i, double width) in columnWidths.indexed) {final (bool firstColumn, bool lastColumn) = (i == 0, i == columnWidths.length - 1);double offAxisFraction = 0.0;Widget? selectionOverlay = _centerSelectionOverlay;if (widget.selectionOverlayBuilder != null) {selectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: i,columnCount: columnWidths.length,);} else {if (firstColumn) {selectionOverlay = _startSelectionOverlay;} else if (lastColumn) {selectionOverlay = _endSelectionOverlay;}}if (firstColumn) {offAxisFraction = -_kMaximumOffAxisFraction * textDirectionFactor;} else if (i >= 2 || columnWidths.length == 2) {offAxisFraction = _kMaximumOffAxisFraction * textDirectionFactor;}EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);if (lastColumn) {padding = padding.flipped;}if (textDirectionFactor == -1) {padding = padding.flipped;}totalColumnWidths += width + (2 * _kDatePickerPadSize);pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction, (BuildContext context, Widget? child) {late final Widget constrained = ConstrainedBox(constraints: BoxConstraints(maxWidth: width + _kDatePickerPadSize),child: child,);return Padding(padding: padding,child: Align(alignment: lastColumn ? alignCenterLeft : alignCenterRight,child: firstColumn || lastColumn ? constrained : child,),);}, selectionOverlay),),);}final double maxPickerWidth =totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(12 unmodified lines}class _CupertinoDatePickerDateState extends State<CupertinoDatePicker> {_CupertinoDatePickerDateState({required this.dateOrder});final DatePickerDateOrder? dateOrder;71 unmodified lines}void _refreshEstimatedColumnWidths() {estimatedColumnWidths[_PickerColumnType.dayOfMonth.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.dayOfMonth,localizations,context,widget.showDayOfWeek,);estimatedColumnWidths[_PickerColumnType.month.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.month,localizations,context,widget.showDayOfWeek,);estimatedColumnWidths[_PickerColumnType.year.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.year,localizations,context,widget.showDayOfWeek,);}// 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);Widget _buildDayPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {final int daysInCurrentMonth = _lastDayInMonth(selectedYear, selectedMonth).day;return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {24 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(31, (int index) {final int day = index + 1;final int? dayOfWeek =widget.showDayOfWeek ? DateTime(selectedYear, selectedMonth, day).weekday : null;final bool isInvalidDay =(day > daysInCurrentMonth) ||(widget.minimumDate?.year == selectedYear &&widget.minimumDate!.month == selectedMonth &&widget.minimumDate!.day > day) ||(widget.maximumDate?.year == selectedYear &&widget.maximumDate!.month == selectedMonth &&widget.maximumDate!.day < day);return itemPositioningBuilder(context,Text(localizations.datePickerDayOfMonth(day, dayOfWeek),style: _themeTextStyle(context, isValid: !isInvalidDay),),);}),1 unmodified line);}Widget _buildMonthPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {23 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(12, (int index) {final int month = index + 1;final bool isInvalidMonth =(widget.minimumDate?.year == selectedYear && widget.minimumDate!.month > month) ||(widget.maximumDate?.year == selectedYear && widget.maximumDate!.month < month);final String monthName =(widget.mode == CupertinoDatePickerMode.monthYear)? localizations.datePickerStandaloneMonth(month): localizations.datePickerMonth(month);return itemPositioningBuilder(context,Text(monthName, style: _themeTextStyle(context, isValid: !isInvalidMonth)),);}),),);}Widget _buildYearPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {12 unmodified linesuseMagnifier: _kUseMagnifier,magnification: _kMagnification,backgroundColor: widget.backgroundColor,squeeze: _kSqueeze,onSelectedItemChanged: (int index) {selectedYear = index;if (_isCurrentDateValid) {9 unmodified linesreturn null;}final bool isValidYear =(widget.minimumDate == null || widget.minimumDate!.year <= year) &&(widget.maximumDate == null || widget.maximumDate!.year >= year);return itemPositioningBuilder(context,23 unmodified linesvoid _pickerDidStopScrolling() {// Call setState to update the greyed out days/months/years, as the currently// selected year/month may have changed.setState(() {});if (isScrolling) {return;43 unmodified linesList<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[];List<double> columnWidths = <double>[];final DatePickerDateOrder datePickerDateOrder = dateOrder ?? localizations.datePickerDateOrder;switch (datePickerDateOrder) {case DatePickerDateOrder.mdy:29 unmodified linesfinal List<Widget> pickers = <Widget>[];double totalColumnWidths = 4 * _kDatePickerPadSize;for (final (int i, double width) in columnWidths.indexed) {final (bool firstColumn, bool lastColumn) = (i == 0, i == columnWidths.length - 1);final double offAxisFraction = (i - 1) * 0.3 * textDirectionFactor;EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize);1 unmodified linepadding = const EdgeInsets.only(left: _kDatePickerPadSize);}Widget? selectionOverlay = _centerSelectionOverlay;if (widget.selectionOverlayBuilder != null) {selectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: i,columnCount: columnWidths.length,);} else {if (firstColumn) {selectionOverlay = _startSelectionOverlay;} else if (lastColumn) {selectionOverlay = _endSelectionOverlay;}}totalColumnWidths += width + (2 * _kDatePickerPadSize);pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction, (BuildContext context, Widget? child) {return Padding(padding: firstColumn ? EdgeInsets.zero : padding,child: Align(alignment: lastColumn ? alignCenterLeft : alignCenterRight,child: SizedBox(width: width + _kDatePickerPadSize,child: Align(alignment: firstColumn ? alignCenterLeft : alignCenterRight,child: child,),),),);}, selectionOverlay),),);}final double maxPickerWidth =totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(12 unmodified lines}class _CupertinoDatePickerMonthYearState extends State<CupertinoDatePicker> {_CupertinoDatePickerMonthYearState({required this.dateOrder});final DatePickerDateOrder? dateOrder;65 unmodified lines}void _refreshEstimatedColumnWidths() {estimatedColumnWidths[_PickerColumnType.month.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.month,localizations,context,false,standaloneMonth: widget.mode == CupertinoDatePickerMode.monthYear,);estimatedColumnWidths[_PickerColumnType.year.index] = CupertinoDatePicker._getColumnWidth(_PickerColumnType.year,localizations,context,false,);}Widget _buildMonthPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {23 unmodified linesselectionOverlay: selectionOverlay,children: List<Widget>.generate(12, (int index) {final int month = index + 1;final bool isInvalidMonth =(widget.minimumDate?.year == selectedYear && widget.minimumDate!.month > month) ||(widget.maximumDate?.year == selectedYear && widget.maximumDate!.month < month);final String monthName =(widget.mode == CupertinoDatePickerMode.monthYear)? localizations.datePickerStandaloneMonth(month): localizations.datePickerMonth(month);return itemPositioningBuilder(context,Text(monthName, style: _themeTextStyle(context, isValid: !isInvalidMonth)),);}),),);}Widget _buildYearPicker(double offAxisFraction,TransitionBuilder itemPositioningBuilder,Widget? selectionOverlay,) {return NotificationListener<ScrollNotification>(onNotification: (ScrollNotification notification) {if (notification is ScrollStartNotification) {27 unmodified linesreturn null;}final bool isValidYear =(widget.minimumDate == null || widget.minimumDate!.year <= year) &&(widget.maximumDate == null || widget.maximumDate!.year >= year);return itemPositioningBuilder(context,11 unmodified linesbool get _isCurrentDateValid {// The current date selection represents a range [minSelectedData, maxSelectDate].final DateTime minSelectedDate = DateTime(selectedYear, selectedMonth);final DateTime maxSelectedDate = DateTime(selectedYear,selectedMonth,widget.initialDateTime.day + 1,);final bool minCheck = widget.minimumDate?.isBefore(maxSelectedDate) ?? true;final bool maxCheck = widget.maximumDate?.isBefore(minSelectedDate) ?? false;5 unmodified linesvoid _pickerDidStopScrolling() {// Call setState to update the greyed out days/months/years, as the currently// selected year/month may have changed.setState(() {});if (isScrolling) {return;2 unmodified lines// Whenever scrolling lands on an invalid entry, the picker// automatically scrolls to a valid one.final DateTime minSelectDate = DateTime(selectedYear, selectedMonth);final DateTime maxSelectDate = DateTime(selectedYear,selectedMonth,widget.initialDateTime.day + 1,);final bool minCheck = widget.minimumDate?.isBefore(maxSelectDate) ?? true;final bool maxCheck = widget.maximumDate?.isBefore(minSelectDate) ?? false;23 unmodified linesList<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[];List<double> columnWidths = <double>[];final DatePickerDateOrder datePickerDateOrder = dateOrder ?? localizations.datePickerDateOrder;switch (datePickerDateOrder) {case DatePickerDateOrder.mdy:15 unmodified linesfinal List<Widget> pickers = <Widget>[];double totalColumnWidths = 3 * _kDatePickerPadSize;for (final (int i, double width) in columnWidths.indexed) {final (bool firstColumn, bool lastColumn) = (i == 0, i == columnWidths.length - 1);final double offAxisFraction = textDirectionFactor * (firstColumn ? -0.3 : 0.5);totalColumnWidths += width + (2 * _kDatePickerPadSize);Widget? selectionOverlay = _centerSelectionOverlay;if (widget.selectionOverlayBuilder != null) {selectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: i,columnCount: columnWidths.length,);} else {if (firstColumn) {selectionOverlay = _startSelectionOverlay;} else if (lastColumn) {selectionOverlay = _endSelectionOverlay;}}pickers.add(LayoutId(id: i,child: pickerBuilders[i](offAxisFraction, (BuildContext context, Widget? child) {final Widget contents = Align(alignment: lastColumn ? alignCenterLeft : alignCenterRight,child: SizedBox(width: width + _kDatePickerPadSize,child: Align(alignment: firstColumn ? alignCenterLeft : alignCenterRight,child: child,),),);if (firstColumn) {return contents;}const EdgeInsets padding = EdgeInsets.only(right: _kDatePickerPadSize);return Padding(padding: textDirectionFactor == -1 ? padding.flipped : padding,child: contents,);}, selectionOverlay),),);}final double maxPickerWidth =totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth;return MediaQuery.withNoTextScaling(child: DefaultTextStyle.merge(26 unmodified lines// If the maximum width given to the picker is smaller than 320.0, the picker's// layout will be broken./// Different modes of [CupertinoTimerPicker].////// See also:5 unmodified lines////// Examples: 16 hours | 14 min.hm,/// Mode that shows the timer duration in minute and second.////// Examples: 14 min | 43 sec.ms,/// Mode that shows the timer duration in hour, minute, and second.////// Examples: 16 hours | 14 min | 43 sec.51 unmodified linesthis.backgroundColor,this.itemExtent = _kItemExtent,required this.onTimerDurationChanged,this.selectionOverlayBuilder,}) : assert(initialTimerDuration >= Duration.zero),assert(initialTimerDuration < const Duration(days: 1)),assert(minuteInterval > 0 && 60 % minuteInterval == 0),assert(secondInterval > 0 && 60 % secondInterval == 0),assert(initialTimerDuration.inMinutes % minuteInterval == 0),assert(initialTimerDuration.inSeconds % secondInterval == 0),assert(itemExtent > 0, 'item extent should be greater than 0');/// The mode of the timer picker.final CupertinoTimerPickerMode mode;27 unmodified lines/// Defaults to a value that matches the default iOS timer picker wheel.final double itemExtent;/// A function that returns a widget that is overlaid on the picker/// to highlight the currently selected entry.////// If unspecified, it defaults to a [CupertinoPickerDefaultSelectionOverlay]/// which is a gray rounded rectangle overlay in iOS 14 style.////// If the selection overlay builder returns null, no overlay will be drawn.////// {@tool snippet}////// This example shows how to recreate the default selection overlay/// with selectionOverlayBuilder.////// ```dart/// CupertinoTimerPicker(/// onTimerDurationChanged: (Duration newDateTime) {},/// selectionOverlayBuilder: (/// BuildContext context, {/// required int selectedIndex,/// required int columnCount,/// }) {/// if (selectedIndex == 0) {/// return const CupertinoPickerDefaultSelectionOverlay(/// capEndEdge: false,/// );/// } else if (selectedIndex == columnCount - 1) {/// return const CupertinoPickerDefaultSelectionOverlay(/// capStartEdge: false,/// );/// }/// return const CupertinoPickerDefaultSelectionOverlay(/// capStartEdge: false,/// capEndEdge: false,/// );/// },/// )/// ```/// {@end-tool}final SelectionOverlayBuilder? selectionOverlayBuilder;@overrideState<StatefulWidget> createState() => _CupertinoTimerPickerState();}1 unmodified lineclass _CupertinoTimerPickerState extends State<CupertinoTimerPicker> {late TextDirection textDirection;late CupertinoLocalizations localizations;int get textDirectionFactor => switch (textDirection) {TextDirection.ltr => 1,TextDirection.rtl => -1,};// The currently selected values of the picker.int? selectedHour;94 unmodified lines// - If two different 1-digit numbers are of the same width, their corresponding// 2 digit numbers are of the same width.for (final String input in numbers) {textPainter.text = TextSpan(text: input, style: textStyle);textPainter.layout();if (textPainter.maxIntrinsicWidth > maxWidth) {2 unmodified lines}}textPainter.text = TextSpan(text: '$widestNumber$widestNumber', style: textStyle);textPainter.layout();numberLabelWidth = textPainter.maxIntrinsicWidth;numberLabelHeight = textPainter.height;numberLabelBaseline = textPainter.computeDistanceToActualBaseline(TextBaseline.alphabetic);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);}}23 unmodified lines// 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: Padding(padding: padding.resolve(textDirection),child: Align(alignment: AlignmentDirectional.centerStart.resolve(textDirection),child: SizedBox(height: numberLabelHeight,child: Baseline(baseline: numberLabelBaseline,baselineType: TextBaseline.alphabetic,child: Text(text,style: const TextStyle(fontSize: _kTimerPickerLabelFontSize,fontWeight: FontWeight.w600,),maxLines: 1,softWrap: false,),),),),4 unmodified lines// The picker has to be wider than its content, since the separators// are part of the picker.Widget _buildPickerNumberLabel(String text, EdgeInsetsDirectional padding) {return SizedBox(width: _kTimerPickerColumnIntrinsicWidth + padding.horizontal,child: Padding(padding: padding.resolve(textDirection),child: Align(alignment: AlignmentDirectional.centerStart.resolve(textDirection),child: SizedBox(width: numberLabelWidth,child: Align(alignment: AlignmentDirectional.centerEnd.resolve(textDirection),child: Text(text, softWrap: false, maxLines: 1, overflow: TextOverflow.visible),),),),),);}Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {_hourScrollController ??= FixedExtentScrollController(initialItem: selectedHour!);return CupertinoPicker(scrollController: _hourScrollController,magnification: _kMagnification,5 unmodified linessetState(() {selectedHour = index;widget.onTimerDurationChanged(Duration(hours: selectedHour!, minutes: selectedMinute, seconds: selectedSecond ?? 0),);});},selectionOverlay: selectionOverlay,children: List<Widget>.generate(24, (int index) {final String label = localizations.timerPickerHourLabel(index) ?? '';final String semanticsLabel =textDirectionFactor == 1? localizations.timerPickerHour(index) + label: label + localizations.timerPickerHour(index);return Semantics(label: semanticsLabel,4 unmodified lines);}Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() {lastSelectedHour = selectedHour;});return false;},child: _buildHourPicker(additionalPadding, selectionOverlay),6 unmodified lines);}Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {_minuteScrollController ??= FixedExtentScrollController(initialItem: selectedMinute ~/ widget.minuteInterval,);1 unmodified linescrollController: _minuteScrollController,magnification: _kMagnification,offAxisFraction: _calculateOffAxisFraction(additionalPadding.start,widget.mode == CupertinoTimerPickerMode.ms ? 0 : 1,),itemExtent: widget.itemExtent,backgroundColor: widget.backgroundColor,15 unmodified lineschildren: List<Widget>.generate(60 ~/ widget.minuteInterval, (int index) {final int minute = index * widget.minuteInterval;final String label = localizations.timerPickerMinuteLabel(minute) ?? '';final String semanticsLabel =textDirectionFactor == 1? localizations.timerPickerMinute(minute) + label: label + localizations.timerPickerMinute(minute);return Semantics(label: semanticsLabel,excludeSemantics: true,child: _buildPickerNumberLabel(localizations.timerPickerMinute(minute),additionalPadding,),);}),);}Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() {lastSelectedMinute = selectedMinute;});return false;},child: _buildMinutePicker(additionalPadding, selectionOverlay),6 unmodified lines);}Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {_secondScrollController ??= FixedExtentScrollController(initialItem: selectedSecond! ~/ widget.secondInterval,);1 unmodified linescrollController: _secondScrollController,magnification: _kMagnification,offAxisFraction: _calculateOffAxisFraction(additionalPadding.start,widget.mode == CupertinoTimerPickerMode.ms ? 1 : 2,),itemExtent: widget.itemExtent,backgroundColor: widget.backgroundColor,3 unmodified linessetState(() {selectedSecond = index * widget.secondInterval;widget.onTimerDurationChanged(Duration(hours: selectedHour ?? 0, minutes: selectedMinute, seconds: selectedSecond!),);});},1 unmodified linechildren: List<Widget>.generate(60 ~/ widget.secondInterval, (int index) {final int second = index * widget.secondInterval;final String label = localizations.timerPickerSecondLabel(second) ?? '';final String semanticsLabel =textDirectionFactor == 1? localizations.timerPickerSecond(second) + label: label + localizations.timerPickerSecond(second);return Semantics(label: semanticsLabel,excludeSemantics: true,child: _buildPickerNumberLabel(localizations.timerPickerSecond(second),additionalPadding,),);}),);}Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) {additionalPadding = EdgeInsetsDirectional.only(start: math.max(additionalPadding.start, 0),end: math.max(additionalPadding.end, 0),3 unmodified lineschildren: <Widget>[NotificationListener<ScrollEndNotification>(onNotification: (ScrollEndNotification notification) {setState(() {lastSelectedSecond = selectedSecond;});return false;},child: _buildSecondPicker(additionalPadding, selectionOverlay),22 unmodified linesfinal 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;22 unmodified linesif (constraints.maxWidth < totalWidth) {totalWidth = constraints.maxWidth;pickerColumnWidth = totalWidth / (widget.mode == CupertinoTimerPickerMode.hms ? 3 : 2);}final double baseLabelContentWidth = numberLabelWidth + _kTimerPickerLabelPadSize;1 unmodified lineswitch (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;7 unmodified linesminuteColumnEndPadding = _kTimerPickerMinHorizontalPadding;}Widget? hourSelectionOverlay = _startSelectionOverlay;Widget? minuteSelectionOverlay = _endSelectionOverlay;if (widget.selectionOverlayBuilder != null) {hourSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 0,columnCount: 2,);minuteSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 1,columnCount: 2,);}columns = <Widget>[_buildHourColumn(EdgeInsetsDirectional.only(start: hourColumnStartPadding,end: pickerColumnWidth - hourColumnStartPadding - hourLabelContentWidth,),hourSelectionOverlay,),_buildMinuteColumn(EdgeInsetsDirectional.only(start: pickerColumnWidth - minuteColumnEndPadding - minuteLabelContentWidth,end: minuteColumnEndPadding,),minuteSelectionOverlay,),];case CupertinoTimerPickerMode.ms:10 unmodified linesminuteColumnStartPadding = _kTimerPickerMinHorizontalPadding;}Widget? minuteSelectionOverlay = _startSelectionOverlay;Widget? secondSelectionOverlay = _endSelectionOverlay;if (widget.selectionOverlayBuilder != null) {minuteSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 0,columnCount: 2,);secondSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 1,columnCount: 2,);}columns = <Widget>[_buildMinuteColumn(EdgeInsetsDirectional.only(start: minuteColumnStartPadding,end: pickerColumnWidth - minuteColumnStartPadding - minuteLabelContentWidth,),minuteSelectionOverlay,),_buildSecondColumn(EdgeInsetsDirectional.only(start: pickerColumnWidth - secondColumnEndPadding - minuteLabelContentWidth,end: secondColumnEndPadding,),secondSelectionOverlay,),];case CupertinoTimerPickerMode.hms:final double hourColumnEndPadding =pickerColumnWidth -baseLabelContentWidth -hourLabelWidth -_kTimerPickerMinHorizontalPadding;final double minuteColumnPadding = (pickerColumnWidth - minuteLabelContentWidth) / 2;final double secondColumnStartPadding =pickerColumnWidth -baseLabelContentWidth -secondLabelWidth -_kTimerPickerMinHorizontalPadding;Widget? hourSelectionOverlay = _startSelectionOverlay;Widget? minuteSelectionOverlay = _centerSelectionOverlay;Widget? secondSelectionOverlay = _endSelectionOverlay;if (widget.selectionOverlayBuilder != null) {hourSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 0,columnCount: 3,);minuteSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 1,columnCount: 3,);secondSelectionOverlay = widget.selectionOverlayBuilder!(context,selectedIndex: 2,columnCount: 3,);}columns = <Widget>[_buildHourColumn(EdgeInsetsDirectional.only(start: _kTimerPickerMinHorizontalPadding,end: math.max(hourColumnEndPadding, 0),),hourSelectionOverlay,),_buildMinuteColumn(EdgeInsetsDirectional.only(start: minuteColumnPadding, end: minuteColumnPadding),minuteSelectionOverlay,),_buildSecondColumn(EdgeInsetsDirectional.only(start: math.max(secondColumnStartPadding, 0),end: _kTimerPickerMinHorizontalPadding,),secondSelectionOverlay,),];}Widget contents = SizedBox(width: totalWidth,height: _kPickerHeight,child: DefaultTextStyle(style: _textStyleFrom(context),child: Row(children: columns.map((Widget child) => Expanded(child: child)).toList(growable: false),),),);final Color? color = CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context);if (color != null) {contents = ColoredBox(color: color, child: contents);}final CupertinoThemeData themeData = CupertinoTheme.of(context);// Text scaling is fixed to match the native iOS date picker.return MediaQuery.withNoTextScaling(child: CupertinoTheme(data: themeData.copyWith(1 unmodified linepickerTextStyle: _textStyleFrom(context, _kTimerPickerMagnification),),),child: Align(alignment: widget.alignment, child: contents),),);},
12 unmodified lines131415161718192038 unmodified lines5960616263646553 unmodified lines11912012112212312412512612712832 unmodified lines1611621631641651661672 unmodified lines1701711721731741751761771781791801811821831841851861871881891902 unmodified lines19319419519619719819920012 unmodified lines////// Specifically does not manage the toolbar, which is left to/// [EditableText.contextMenuBuilder].class _CupertinoDesktopTextSelectionHandleControls extends CupertinoDesktopTextSelectionControls with TextSelectionHandleControls {}/// Desktop Cupertino styled text selection controls.///38 unmodified lines/// Builds the text selection handles, but desktop has none.@overrideWidget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) {return const SizedBox.shrink();}53 unmodified linesfinal double textLineHeight;@override_CupertinoDesktopTextSelectionControlsToolbarState createState() => _CupertinoDesktopTextSelectionControlsToolbarState();}class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_CupertinoDesktopTextSelectionControlsToolbar> {void _onChangedClipboardStatus() {setState(() {// Inform the widget that the value of clipboardStatus has changed.32 unmodified linesfinal EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);final Offset midpointAnchor = Offset(clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left,mediaQueryPadding.left,MediaQuery.sizeOf(context).width - mediaQueryPadding.right,),2 unmodified linesfinal List<Widget> items = <Widget>[];final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);final Widget onePhysicalPixelVerticalDivider =SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context));void addToolbarButton(String text,VoidCallback onPressed,) {if (items.isNotEmpty) {items.add(onePhysicalPixelVerticalDivider);}items.add(CupertinoDesktopTextSelectionToolbarButton.text(onPressed: onPressed,text: text,));}if (widget.handleCut != null) {2 unmodified linesif (widget.handleCopy != null) {addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!);}if (widget.handlePaste != null&& widget.clipboardStatus?.value == ClipboardStatus.pasteable) {addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!);}if (widget.handleSelectAll != null) {12 unmodified lines131415161718192038 unmodified lines59606162636465666768697053 unmodified lines12412512612712812913013113213313413532 unmodified lines1681691701711721731741752 unmodified lines1781791801811821831841851861871881891901911921932 unmodified lines19619719819920020120212 unmodified lines////// Specifically does not manage the toolbar, which is left to/// [EditableText.contextMenuBuilder].class _CupertinoDesktopTextSelectionHandleControls extends CupertinoDesktopTextSelectionControlswith TextSelectionHandleControls {}/// Desktop Cupertino styled text selection controls.///38 unmodified lines/// Builds the text selection handles, but desktop has none.@overrideWidget buildHandle(BuildContext context,TextSelectionHandleType type,double textLineHeight, [VoidCallback? onTap,]) {return const SizedBox.shrink();}53 unmodified linesfinal double textLineHeight;@override_CupertinoDesktopTextSelectionControlsToolbarState createState() =>_CupertinoDesktopTextSelectionControlsToolbarState();}class _CupertinoDesktopTextSelectionControlsToolbarStateextends State<_CupertinoDesktopTextSelectionControlsToolbar> {void _onChangedClipboardStatus() {setState(() {// Inform the widget that the value of clipboardStatus has changed.32 unmodified linesfinal EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);final Offset midpointAnchor = Offset(clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left,mediaQueryPadding.left,MediaQuery.sizeOf(context).width - mediaQueryPadding.right,),2 unmodified linesfinal List<Widget> items = <Widget>[];final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);final Widget onePhysicalPixelVerticalDivider = SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context),);void addToolbarButton(String text, VoidCallback onPressed) {if (items.isNotEmpty) {items.add(onePhysicalPixelVerticalDivider);}items.add(CupertinoDesktopTextSelectionToolbarButton.text(onPressed: onPressed, text: text));}if (widget.handleCut != null) {2 unmodified linesif (widget.handleCopy != null) {addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!);}if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.pasteable) {addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!);}if (widget.handleSelectAll != null) {
1 unmodified line234567891020 unmodified lines3132333435363738394041424360 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361373 unmodified lines1411421431441451461471484 unmodified lines1531541551561571581591601611621631641651661671 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:ui';import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';20 unmodified lines// These values were measured from a screenshot of the native context menu on// macOS 13.2 on a Macbook Pro.const CupertinoDynamicColor _kToolbarBorderColor =CupertinoDynamicColor.withBrightness(color: Color(0xFFB8B8B8),darkColor: Color(0xFF5B5B5B),);const CupertinoDynamicColor _kToolbarBackgroundColor =CupertinoDynamicColor.withBrightness(color: Color(0xB2FFFFFF),darkColor: Color(0xB2303030),);60 unmodified linesborderRadius: BorderRadius.all(_kToolbarBorderRadius),),child: BackdropFilter(// Flutter web doesn't support ImageFilter.compose on CanvasKit yet// (https://github.com/flutter/flutter/issues/120123).filter: kIsWeb? ImageFilter.blur(sigmaX: _kToolbarBlurSigma,sigmaY: _kToolbarBlurSigma,): ImageFilter.compose(outer: ColorFilter.matrix(_matrixWithSaturation(_kToolbarSaturationBoost),),inner: ImageFilter.blur(sigmaX: _kToolbarBlurSigma,sigmaY: _kToolbarBlurSigma,),),child: DecoratedBox(decoration: BoxDecoration(color: _kToolbarBackgroundColor.resolveFrom(context),border: Border.all(color: _kToolbarBorderColor.resolveFrom(context),),borderRadius: const BorderRadius.all(_kToolbarBorderRadius),),child: Padding(padding: _kToolbarPadding,child: child,),),),);3 unmodified linesWidget build(BuildContext context) {assert(debugCheckHasMediaQuery(context));final double paddingAbove =MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);return Padding(4 unmodified lines_kToolbarScreenPadding,),child: CustomSingleChildLayout(delegate: DesktopTextSelectionToolbarLayoutDelegate(anchor: anchor - localAdjustment,),child: _defaultToolbarBuilder(context,Column(mainAxisSize: MainAxisSize.min,children: children,),),),);1 unmodified line2345678910111213141520 unmodified lines363738394041424344454660 unmodified lines1071081091101111121131141151161171181191201211221233 unmodified lines1271281291301311321334 unmodified lines1381391401411421431441451461471 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'adaptive_text_selection_toolbar.dart';/// @docImport 'desktop_text_selection_toolbar_button.dart';library;import 'dart:ui';import 'package:flutter/widgets.dart';import 'colors.dart';20 unmodified lines// These values were measured from a screenshot of the native context menu on// macOS 13.2 on a Macbook Pro.const CupertinoDynamicColor _kToolbarBorderColor = CupertinoDynamicColor.withBrightness(color: Color(0xFFB8B8B8),darkColor: Color(0xFF5B5B5B),);const CupertinoDynamicColor _kToolbarBackgroundColor = CupertinoDynamicColor.withBrightness(color: Color(0xB2FFFFFF),darkColor: Color(0xB2303030),);60 unmodified linesborderRadius: BorderRadius.all(_kToolbarBorderRadius),),child: BackdropFilter(filter: ImageFilter.compose(outer: ColorFilter.matrix(_matrixWithSaturation(_kToolbarSaturationBoost)),inner: ImageFilter.blur(sigmaX: _kToolbarBlurSigma, sigmaY: _kToolbarBlurSigma),),child: DecoratedBox(decoration: BoxDecoration(color: _kToolbarBackgroundColor.resolveFrom(context),border: Border.all(color: _kToolbarBorderColor.resolveFrom(context)),borderRadius: const BorderRadius.all(_kToolbarBorderRadius),),child: Padding(padding: _kToolbarPadding, child: child),),),);3 unmodified linesWidget build(BuildContext context) {assert(debugCheckHasMediaQuery(context));final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);return Padding(4 unmodified lines_kToolbarScreenPadding,),child: CustomSingleChildLayout(delegate: DesktopTextSelectionToolbarLayoutDelegate(anchor: anchor - localAdjustment),child: _defaultToolbarBuilder(context,Column(mainAxisSize: MainAxisSize.min, children: children),),),);
20 unmodified lines2122232425262728293031322 unmodified lines35363738394041421 unmodified line444546474849505152535455565758596030 unmodified lines91929394959697989910010110210310410510610710810911011120 unmodified lines// This value was measured from a screenshot of the native context menu on// macOS 13.2 on a Macbook Pro.const EdgeInsets _kToolbarButtonPadding = EdgeInsets.fromLTRB(8.0,2.0,8.0,5.0,);/// A button in the style of the Mac context menu buttons.class CupertinoDesktopTextSelectionToolbarButton extends StatefulWidget {2 unmodified linessuper.key,required this.onPressed,required Widget this.child,}) : buttonItem = null,text = null;/// Create an instance of [CupertinoDesktopTextSelectionToolbarButton] whose child is/// a [Text] widget styled like the default Mac context menu button.1 unmodified linesuper.key,required this.onPressed,required this.text,}) : buttonItem = null,child = null;/// Create an instance of [CupertinoDesktopTextSelectionToolbarButton] from/// the given [ContextMenuButtonItem].CupertinoDesktopTextSelectionToolbarButton.buttonItem({super.key,required ContextMenuButtonItem this.buttonItem,}) : onPressed = buttonItem.onPressed,text = null,child = null;/// {@macro flutter.cupertino.CupertinoTextSelectionToolbarButton.onPressed}final VoidCallback? onPressed;30 unmodified lines@overrideWidget build(BuildContext context) {final Widget child = widget.child ??Text(widget.text ??CupertinoTextSelectionToolbarButton.getButtonLabel(context,widget.buttonItem!,),overflow: TextOverflow.ellipsis,style: _kToolbarButtonFontStyle.copyWith(color: _isHovered? CupertinoTheme.of(context).primaryContrastingColor: const CupertinoDynamicColor.withBrightness(color: CupertinoColors.black,darkColor: CupertinoColors.white,).resolveFrom(context),),);20 unmodified lines212223242526272 unmodified lines30313233343536371 unmodified line394041424344454647484950515253545530 unmodified lines868788899091929394959697989910010110210310410520 unmodified lines// This value was measured from a screenshot of the native context menu on// macOS 13.2 on a Macbook Pro.const EdgeInsets _kToolbarButtonPadding = EdgeInsets.fromLTRB(8.0, 2.0, 8.0, 5.0);/// A button in the style of the Mac context menu buttons.class CupertinoDesktopTextSelectionToolbarButton extends StatefulWidget {2 unmodified linessuper.key,required this.onPressed,required Widget this.child,}) : buttonItem = null,text = null;/// Create an instance of [CupertinoDesktopTextSelectionToolbarButton] whose child is/// a [Text] widget styled like the default Mac context menu button.1 unmodified linesuper.key,required this.onPressed,required this.text,}) : buttonItem = null,child = null;/// Create an instance of [CupertinoDesktopTextSelectionToolbarButton] from/// the given [ContextMenuButtonItem].CupertinoDesktopTextSelectionToolbarButton.buttonItem({super.key,required ContextMenuButtonItem this.buttonItem,}) : onPressed = buttonItem.onPressed,text = null,child = null;/// {@macro flutter.cupertino.CupertinoTextSelectionToolbarButton.onPressed}final VoidCallback? onPressed;30 unmodified lines@overrideWidget build(BuildContext context) {final Widget child =widget.child ??Text(widget.text ??CupertinoTextSelectionToolbarButton.getButtonLabel(context, widget.buttonItem!),overflow: TextOverflow.ellipsis,style: _kToolbarButtonFontStyle.copyWith(color:_isHovered? CupertinoTheme.of(context).primaryContrastingColor: const CupertinoDynamicColor.withBrightness(color: CupertinoColors.black,darkColor: CupertinoColors.white,).resolveFrom(context),),);
1 unmodified line2345678910111213141597 unmodified lines1131141151161171181193 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'colors.dart';import 'theme.dart';// Content padding determined via SwiftUI's `Form` view in the iOS 14.2 SDK.const EdgeInsetsGeometry _kDefaultPadding =EdgeInsetsDirectional.fromSTEB(20.0, 6.0, 6.0, 6.0);/// An iOS-style form row.///97 unmodified linesWidget build(BuildContext context) {final CupertinoThemeData theme = CupertinoTheme.of(context);final TextStyle textStyle = theme.textTheme.textStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(theme.textTheme.textStyle.color, context));return Padding(3 unmodified linesRow(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[if (prefix != null)DefaultTextStyle(style: textStyle,child: prefix!,),Flexible(child: Align(alignment: AlignmentDirectional.centerEnd,child: child,),),],),if (helper != null)Align(alignment: AlignmentDirectional.centerStart,child: DefaultTextStyle(style: textStyle,child: helper!,),),if (error != null)Align(1 unmodified line23456789101112131415161797 unmodified lines1151161171181191201213 unmodified lines1251261271281291301311321331341351361371381 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'form_section.dart';library;import 'package:flutter/widgets.dart';import 'colors.dart';import 'theme.dart';// Content padding determined via SwiftUI's `Form` view in the iOS 14.2 SDK.const EdgeInsetsGeometry _kDefaultPadding = EdgeInsetsDirectional.fromSTEB(20.0, 6.0, 6.0, 6.0);/// An iOS-style form row.///97 unmodified linesWidget build(BuildContext context) {final CupertinoThemeData theme = CupertinoTheme.of(context);final TextStyle textStyle = theme.textTheme.textStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(theme.textTheme.textStyle.color, context),);return Padding(3 unmodified linesRow(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[if (prefix != null) DefaultTextStyle(style: textStyle, child: prefix!),Flexible(child: Align(alignment: AlignmentDirectional.centerEnd, child: child)),],),if (helper != null)Align(alignment: AlignmentDirectional.centerStart,child: DefaultTextStyle(style: textStyle, child: helper!),),if (error != null)Align(
1 unmodified line2345671 unmodified line910111213141580 unmodified lines9697989910010110210338 unmodified lines14214314414514614714814942 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'colors.dart';1 unmodified line// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kFormDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);/// An iOS-style form section.///80 unmodified linesthis.backgroundColor = CupertinoColors.systemGroupedBackground,this.decoration,this.clipBehavior = Clip.none,}) : _type = CupertinoListSectionType.base,assert(children.length > 0);/// Creates a section that mimics standard "Inset Grouped" iOS forms.///38 unmodified linesthis.backgroundColor = CupertinoColors.systemGroupedBackground,this.decoration,this.clipBehavior = Clip.none,}) : _type = CupertinoListSectionType.insetGrouped,assert(children.length > 0);final CupertinoListSectionType _type;42 unmodified lines@overrideWidget build(BuildContext context) {final Widget? headerWidget = header == null? null: DefaultTextStyle(style: TextStyle(fontSize: 13.0,color: CupertinoColors.secondaryLabel.resolveFrom(context),),child: header!);final Widget? footerWidget = footer == null? null: DefaultTextStyle(style: TextStyle(fontSize: 13.0,color: CupertinoColors.secondaryLabel.resolveFrom(context),),child: footer!);return _type == CupertinoListSectionType.base? CupertinoListSection(header: headerWidget,footer: footerWidget,margin: margin,backgroundColor: backgroundColor,decoration: decoration,clipBehavior: clipBehavior,hasLeading: false,children: children): CupertinoListSection.insetGrouped(header: headerWidget,footer: footerWidget,margin: margin,backgroundColor: backgroundColor,decoration: decoration,clipBehavior: clipBehavior,hasLeading: false,children: children);}}1 unmodified line2345678910111 unmodified line13141516171819202122232480 unmodified lines10510610710810911011111238 unmodified lines15115215315415515615715842 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502511 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'form_row.dart';/// @docImport 'text_form_field_row.dart';library;import 'package:flutter/widgets.dart';import 'colors.dart';1 unmodified line// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kFormDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0,0.0,20.0,10.0,);/// An iOS-style form section.///80 unmodified linesthis.backgroundColor = CupertinoColors.systemGroupedBackground,this.decoration,this.clipBehavior = Clip.none,}) : _type = CupertinoListSectionType.base,assert(children.length > 0);/// Creates a section that mimics standard "Inset Grouped" iOS forms.///38 unmodified linesthis.backgroundColor = CupertinoColors.systemGroupedBackground,this.decoration,this.clipBehavior = Clip.none,}) : _type = CupertinoListSectionType.insetGrouped,assert(children.length > 0);final CupertinoListSectionType _type;42 unmodified lines@overrideWidget build(BuildContext context) {final Widget? headerWidget =header == null? null: DefaultTextStyle(style: TextStyle(fontSize: 13.0,color: CupertinoColors.secondaryLabel.resolveFrom(context),),child: header!,);final Widget? footerWidget =footer == null? null: DefaultTextStyle(style: TextStyle(fontSize: 13.0,color: CupertinoColors.secondaryLabel.resolveFrom(context),),child: footer!,);switch (_type) {case CupertinoListSectionType.base:return CupertinoListSection(header: headerWidget,footer: footerWidget,margin: margin,backgroundColor: backgroundColor,decoration: decoration,clipBehavior: clipBehavior,hasLeading: false,children: children,);case CupertinoListSectionType.insetGrouped:return CupertinoListSection.insetGrouped(header: headerWidget,footer: footerWidget,margin: margin,backgroundColor: backgroundColor,decoration: decoration,clipBehavior: clipBehavior,hasLeading: false,children: children,);}}}
63 unmodified lines6465666768697022 unmodified lines9394959697989910010110210363 unmodified lines/// * [maybeOf], which is similar, but will return null if no/// [CupertinoUserInterfaceLevel] encloses the given context.static CupertinoUserInterfaceLevelData of(BuildContext context) {final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();if (query != null) {return query._data;}22 unmodified lines/// * [of], which is similar, but will throw an exception if no/// [CupertinoUserInterfaceLevel] encloses the given context.static CupertinoUserInterfaceLevelData? maybeOf(BuildContext context) {final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();if (query != null) {return query._data;}return null;}@override63 unmodified lines646566676869707122 unmodified lines94959697989910010110263 unmodified lines/// * [maybeOf], which is similar, but will return null if no/// [CupertinoUserInterfaceLevel] encloses the given context.static CupertinoUserInterfaceLevelData of(BuildContext context) {final CupertinoUserInterfaceLevel? query =context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();if (query != null) {return query._data;}22 unmodified lines/// * [of], which is similar, but will throw an exception if no/// [CupertinoUserInterfaceLevel] encloses the given context.static CupertinoUserInterfaceLevelData? maybeOf(BuildContext context) {final CupertinoUserInterfaceLevel? query =context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();return query?._data;}@override
1 unmodified line2345674 unmodified lines121314151617181920212223242526271 unmodified line2930313233343536373839174 unmodified lines21421521621721821922022156 unmodified lines27827928028128228328428528628728870 unmodified lines35936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440524 unmodified lines4304314324334344354364374384394404411 unmodified line4434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834841 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'colors.dart';4 unmodified linesconst double _kMarginTop = 22.0;// Standard header margin, determined from SwiftUI's Forms in iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultHeaderMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 6.0);// Header margin for inset grouped variant, determined from iOS 14.4 Simulator.const EdgeInsetsDirectional _kInsetGroupedDefaultHeaderMargin = EdgeInsetsDirectional.fromSTEB(20.0, 16.0, 20.0, 6.0);// Standard footer margin, determined from SwiftUI's Forms in iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultFooterMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 0.0);// Footer margin for inset grouped variant, determined from iOS 14.4 Simulator.const EdgeInsetsDirectional _kInsetGroupedDefaultFooterMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);// Margin around children in edge-to-edge variant, determined from iOS 14.4// Simulator.1 unmodified line// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0, 20.0, 20.0, 10.0);// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultInsetGroupedRowsMarginWithHeader = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);// Used for iOS "Inset Grouped" border radius, estimated from SwiftUI's Forms in// iOS 14.2 SDK.174 unmodified linesthis.separatorColor,}) : assert((children != null && children.length > 0) || header != null),type = CupertinoListSectionType.base,additionalDividerMargin = additionalDividerMargin ??(hasLeading ? _kBaseAdditionalDividerMargin : 0.0);/// Creates a section that mimics standard "Inset Grouped" iOS list section.///56 unmodified linesthis.separatorColor,}) : assert((children != null && children.length > 0) || header != null),type = CupertinoListSectionType.insetGrouped,additionalDividerMargin = additionalDividerMargin ??(hasLeading? _kInsetAdditionalDividerMargin: _kInsetAdditionalDividerMarginWithoutLeading),margin = margin ?? (header == null ? _kDefaultInsetGroupedRowsMargin : _kDefaultInsetGroupedRowsMarginWithHeader);/// The type of list section, either base or inset grouped.///70 unmodified lines// Long divider is used for wrapping the top and bottom of rows.// Only used in CupertinoListSectionType.base mode.final Widget longDivider = Container(color: dividerColor,height: dividerHeight,);// Short divider is used between rows.final Widget shortDivider = Container(margin: EdgeInsetsDirectional.only(start: dividerMargin + additionalDividerMargin),color: dividerColor,height: dividerHeight,);Widget? headerWidget;if (header != null) {headerWidget = DefaultTextStyle(style: CupertinoTheme.of(context).textTheme.textStyle.merge(type == CupertinoListSectionType.base? TextStyle(fontSize: 13.0,color: CupertinoDynamicColor.resolve(_kHeaderFooterColor, context)): const TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),child: header!,);}Widget? footerWidget;if (footer != null) {footerWidget = DefaultTextStyle(style: type == CupertinoListSectionType.base? CupertinoTheme.of(context).textTheme.textStyle.merge(TextStyle(fontSize: 13.0,color: CupertinoDynamicColor.resolve(_kHeaderFooterColor, context),)): CupertinoTheme.of(context).textTheme.textStyle,child: footer!,);}Widget? decoratedChildrenGroup;24 unmodified lines};decoratedChildrenGroup = DecoratedBox(decoration: decoration ??BoxDecoration(color: CupertinoDynamicColor.resolve(decoration?.color ??CupertinoColors.secondarySystemGroupedBackground,context),borderRadius: childrenGroupBorderRadius,),child: Column(children: childrenWithDividers),1 unmodified linedecoratedChildrenGroup = Padding(padding: margin,child: clipBehavior == Clip.none? decoratedChildrenGroup: ClipRRect(borderRadius: childrenGroupBorderRadius,clipBehavior: clipBehavior,child: decoratedChildrenGroup,),);}return DecoratedBox(decoration: BoxDecoration(color: CupertinoDynamicColor.resolve(backgroundColor, context)),child: Column(children: <Widget>[if (type == CupertinoListSectionType.base)SizedBox(height: topMargin),if (headerWidget != null)Align(alignment: AlignmentDirectional.centerStart,child: Padding(padding: type == CupertinoListSectionType.base? _kDefaultHeaderMargin: _kInsetGroupedDefaultHeaderMargin,child: headerWidget,),),if (decoratedChildrenGroup != null)decoratedChildrenGroup,if (footerWidget != null)Align(alignment: AlignmentDirectional.centerStart,child: Padding(padding: type == CupertinoListSectionType.base? _kDefaultFooterMargin: _kInsetGroupedDefaultFooterMargin,child: footerWidget,),),1 unmodified line23456789101112134 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152531 unmodified line5556575859606162636465666768697071174 unmodified lines24624724824925025125225356 unmodified lines31031131231331431531631731831932032132232332432570 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643724 unmodified lines4624634644654664674684694704714724734741 unmodified line4764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165171 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'form_row.dart';/// @docImport 'form_section.dart';/// @docImport 'list_tile.dart';/// @docImport 'text_form_field_row.dart';library;import 'package:flutter/widgets.dart';import 'colors.dart';4 unmodified linesconst double _kMarginTop = 22.0;// Standard header margin, determined from SwiftUI's Forms in iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultHeaderMargin = EdgeInsetsDirectional.fromSTEB(20.0,0.0,20.0,6.0,);// Header margin for inset grouped variant, determined from iOS 14.4 Simulator.const EdgeInsetsDirectional _kInsetGroupedDefaultHeaderMargin = EdgeInsetsDirectional.fromSTEB(20.0,16.0,20.0,6.0,);// Standard footer margin, determined from SwiftUI's Forms in iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultFooterMargin = EdgeInsetsDirectional.fromSTEB(20.0,0.0,20.0,0.0,);// Footer margin for inset grouped variant, determined from iOS 14.4 Simulator.const EdgeInsetsDirectional _kInsetGroupedDefaultFooterMargin = EdgeInsetsDirectional.fromSTEB(20.0,0.0,20.0,10.0,);// Margin around children in edge-to-edge variant, determined from iOS 14.4// Simulator.1 unmodified line// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0,20.0,20.0,10.0,);// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in// iOS 14.2 SDK.const EdgeInsetsDirectional _kDefaultInsetGroupedRowsMarginWithHeader =EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);// Used for iOS "Inset Grouped" border radius, estimated from SwiftUI's Forms in// iOS 14.2 SDK.174 unmodified linesthis.separatorColor,}) : assert((children != null && children.length > 0) || header != null),type = CupertinoListSectionType.base,additionalDividerMargin =additionalDividerMargin ?? (hasLeading ? _kBaseAdditionalDividerMargin : 0.0);/// Creates a section that mimics standard "Inset Grouped" iOS list section.///56 unmodified linesthis.separatorColor,}) : assert((children != null && children.length > 0) || header != null),type = CupertinoListSectionType.insetGrouped,additionalDividerMargin =additionalDividerMargin ??(hasLeading? _kInsetAdditionalDividerMargin: _kInsetAdditionalDividerMarginWithoutLeading),margin =margin ??(header == null? _kDefaultInsetGroupedRowsMargin: _kDefaultInsetGroupedRowsMarginWithHeader);/// The type of list section, either base or inset grouped.///70 unmodified lines// Long divider is used for wrapping the top and bottom of rows.// Only used in CupertinoListSectionType.base mode.final Widget longDivider = Container(color: dividerColor, height: dividerHeight);// Short divider is used between rows.final Widget shortDivider = Container(margin: EdgeInsetsDirectional.only(start: dividerMargin + additionalDividerMargin),color: dividerColor,height: dividerHeight,);TextStyle style = CupertinoTheme.of(context).textTheme.textStyle;Widget? headerWidget, footerWidget;switch (type) {case CupertinoListSectionType.base:style = style.merge(TextStyle(fontSize: 13.0,color: CupertinoDynamicColor.resolve(_kHeaderFooterColor, context),),);if (header != null) {headerWidget = DefaultTextStyle(style: style, child: header!);}if (footer != null) {footerWidget = DefaultTextStyle(style: style, child: footer!);}case CupertinoListSectionType.insetGrouped:if (header != null) {headerWidget = DefaultTextStyle(style: style.merge(const TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),child: header!,);}if (footer != null) {footerWidget = DefaultTextStyle(style: style, child: footer!);}}Widget? decoratedChildrenGroup;24 unmodified lines};decoratedChildrenGroup = DecoratedBox(decoration:decoration ??BoxDecoration(color: CupertinoDynamicColor.resolve(decoration?.color ?? CupertinoColors.secondarySystemGroupedBackground,context,),borderRadius: childrenGroupBorderRadius,),child: Column(children: childrenWithDividers),1 unmodified linedecoratedChildrenGroup = Padding(padding: margin,child:clipBehavior == Clip.none? decoratedChildrenGroup: ClipRRect(borderRadius: childrenGroupBorderRadius,clipBehavior: clipBehavior,child: decoratedChildrenGroup,),);}return DecoratedBox(decoration: BoxDecoration(color: CupertinoDynamicColor.resolve(backgroundColor, context)),child: Column(children: <Widget>[if (type == CupertinoListSectionType.base) SizedBox(height: topMargin),if (headerWidget != null)Align(alignment: AlignmentDirectional.centerStart,child: Padding(padding:type == CupertinoListSectionType.base? _kDefaultHeaderMargin: _kInsetGroupedDefaultHeaderMargin,child: headerWidget,),),if (decoratedChildrenGroup != null) decoratedChildrenGroup,if (footerWidget != null)Align(alignment: AlignmentDirectional.centerStart,child: Padding(padding:type == CupertinoListSectionType.base? _kDefaultFooterMargin: _kInsetGroupedDefaultFooterMargin,child: footerWidget,),),
1 unmodified line23456711 unmodified lines19202122232425262735 unmodified lines636465666768182 unmodified lines2512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193201 unmodified line3223233243253263273283293303313323333343353363372 unmodified lines3403413423433443453463473483493503513523533 unmodified lines3573583593603613623633643653663673683693703713723733743754 unmodified lines3803813823833843853863873883893903911 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:async';import 'package:flutter/widgets.dart';11 unmodified linesconst double _kNotchedMinHeight = _kNotchedLeadingSize + 2 * 12.0;const double _kNotchedMinHeightWithoutLeading = _kNotchedLeadingSize + 2 * 10.0;const EdgeInsetsDirectional _kPadding = EdgeInsetsDirectional.only(start: 20.0, end: 14.0);const EdgeInsetsDirectional _kPaddingWithSubtitle = EdgeInsetsDirectional.only(start: 20.0, end: 14.0);const EdgeInsets _kNotchedPadding = EdgeInsets.symmetric(horizontal: 14.0);const EdgeInsetsDirectional _kNotchedPaddingWithoutLeading = EdgeInsetsDirectional.fromSTEB(28.0, 10.0, 14.0, 10.0);const double _kLeadingToTitle = 16.0;const double _kNotchedLeadingToTitle = 12.0;const double _kNotchedTitleToSubtitle = 3.0;35 unmodified lines/// behavior it should not be used for example to toggle the [CupertinoSwitch]/// in the trailing widget.////// See also:////// * [CupertinoListSection], an iOS-style list that is a typical container for182 unmodified lines@overrideWidget build(BuildContext context) {final TextStyle titleTextStyle =widget._type == _CupertinoListTileType.base || widget.subtitle == null? CupertinoTheme.of(context).textTheme.textStyle: CupertinoTheme.of(context).textTheme.textStyle.merge(TextStyle(fontWeight: FontWeight.w600,fontSize: widget.leading == null ? _kNotchedTitleWithSubtitleFontSize : null,),);final TextStyle subtitleTextStyle = widget._type == _CupertinoListTileType.base? CupertinoTheme.of(context).textTheme.textStyle.merge(TextStyle(fontSize: _kSubtitleFontSize,color: CupertinoColors.secondaryLabel.resolveFrom(context),),): CupertinoTheme.of(context).textTheme.textStyle.merge(TextStyle(fontSize: _kNotchedSubtitleFontSize,color: CupertinoColors.secondaryLabel.resolveFrom(context),),);final TextStyle? additionalInfoTextStyle = widget.additionalInfo != null? CupertinoTheme.of(context).textTheme.textStyle.merge(TextStyle(color: CupertinoColors.secondaryLabel.resolveFrom(context))): null;final Widget title = DefaultTextStyle(style: titleTextStyle,maxLines: 1,overflow: TextOverflow.ellipsis,child: widget.title,);EdgeInsetsGeometry? padding = widget.padding;if (padding == null) {switch (widget._type) {case _CupertinoListTileType.base:padding = widget.subtitle == null ? _kPadding : _kPaddingWithSubtitle;case _CupertinoListTileType.notched:padding = widget.leading == null ? _kNotchedPaddingWithoutLeading : _kNotchedPadding;}}Widget? subtitle;if (widget.subtitle != null) {subtitle = DefaultTextStyle(style: subtitleTextStyle,maxLines: 1,overflow: TextOverflow.ellipsis,child: widget.subtitle!,);}Widget? additionalInfo;if (widget.additionalInfo != null) {additionalInfo = DefaultTextStyle(style: additionalInfoTextStyle!,maxLines: 1,child: widget.additionalInfo!,);}// The color for default state tile is set to either what user provided or// null and it will resolve to the correct color provided by context. But if1 unmodified line// default color that matched the iOS-style.Color? backgroundColor = widget.backgroundColor;if (_tapped) {backgroundColor = widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context);}double minHeight;switch (widget._type) {case _CupertinoListTileType.base:minHeight = subtitle == null ? _kMinHeight : _kMinHeightWithSubtitle;case _CupertinoListTileType.notched:minHeight = widget.leading == null ? _kNotchedMinHeightWithoutLeading : _kNotchedMinHeight;}final Widget child = Container(constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight),2 unmodified linespadding: padding,child: Row(children: <Widget>[if (widget.leading != null) ...<Widget>[SizedBox(width: widget.leadingSize,height: widget.leadingSize,child: Center(child: widget.leading,),),SizedBox(width: widget.leadingToTitle),] elseSizedBox(height: widget.leadingSize),3 unmodified linescrossAxisAlignment: CrossAxisAlignment.start,children: <Widget>[title,if (subtitle != null) ...<Widget>[const SizedBox(height: _kNotchedTitleToSubtitle),subtitle,],],),),if (additionalInfo != null) ...<Widget>[additionalInfo,if (widget.trailing != null)const SizedBox(width: _kAdditionalInfoToTrailing),],if (widget.trailing != null) widget.trailing!],),),4 unmodified lines}return GestureDetector(onTapDown: (_) => setState(() { _tapped = true; }),onTapCancel: () => setState(() { _tapped = false; }),onTap: () async {await widget.onTap!();if (mounted) {setState(() { _tapped = false; });}},behavior: HitTestBehavior.opaque,1 unmodified line23456789101112131411 unmodified lines262728293031323334353637383940414235 unmodified lines78798081828384858687888990182 unmodified lines2732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073081 unmodified line3103113123133143153163173183193203213223233243252 unmodified lines3283293303313323333343353 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603613623634 unmodified lines3683693703713723733743753763773783793803813823833843853863871 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'button.dart';/// @docImport 'list_section.dart';/// @docImport 'switch.dart';library;import 'dart:async';import 'package:flutter/widgets.dart';11 unmodified linesconst double _kNotchedMinHeight = _kNotchedLeadingSize + 2 * 12.0;const double _kNotchedMinHeightWithoutLeading = _kNotchedLeadingSize + 2 * 10.0;const EdgeInsetsDirectional _kPadding = EdgeInsetsDirectional.only(start: 20.0, end: 14.0);const EdgeInsetsDirectional _kPaddingWithSubtitle = EdgeInsetsDirectional.only(start: 20.0,end: 14.0,);const EdgeInsets _kNotchedPadding = EdgeInsets.symmetric(horizontal: 14.0);const EdgeInsetsDirectional _kNotchedPaddingWithoutLeading = EdgeInsetsDirectional.fromSTEB(28.0,10.0,14.0,10.0,);const double _kLeadingToTitle = 16.0;const double _kNotchedLeadingToTitle = 12.0;const double _kNotchedTitleToSubtitle = 3.0;35 unmodified lines/// behavior it should not be used for example to toggle the [CupertinoSwitch]/// in the trailing widget.////// {@tool dartpad}/// This example uses a [ListView] to demonstrate different configurations of/// [CupertinoListTile]s.////// ** See code in examples/api/lib/cupertino/list_tile/cupertino_list_tile.0.dart **/// {@end-tool}////// See also:////// * [CupertinoListSection], an iOS-style list that is a typical container for182 unmodified lines@overrideWidget build(BuildContext context) {final TextStyle textStyle = CupertinoTheme.of(context).textTheme.textStyle;final TextStyle coloredStyle = textStyle.copyWith(color: CupertinoColors.secondaryLabel.resolveFrom(context),);final bool baseType = switch (widget._type) {_CupertinoListTileType.base => true,_CupertinoListTileType.notched => false,};final Widget title = DefaultTextStyle(style:baseType || widget.subtitle == null? textStyle: textStyle.copyWith(fontWeight: FontWeight.w600,fontSize: widget.leading == null ? _kNotchedTitleWithSubtitleFontSize : null,),maxLines: 1,overflow: TextOverflow.ellipsis,child: widget.title,);final EdgeInsetsGeometry padding =widget.padding ??switch (widget._type) {_CupertinoListTileType.base when widget.subtitle != null => _kPaddingWithSubtitle,_CupertinoListTileType.notched when widget.leading != null => _kNotchedPadding,_CupertinoListTileType.base => _kPadding,_CupertinoListTileType.notched => _kNotchedPaddingWithoutLeading,};// The color for default state tile is set to either what user provided or// null and it will resolve to the correct color provided by context. But if1 unmodified line// default color that matched the iOS-style.Color? backgroundColor = widget.backgroundColor;if (_tapped) {backgroundColor =widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context);}final double minHeight = switch (widget._type) {_CupertinoListTileType.base when widget.subtitle != null => _kMinHeightWithSubtitle,_CupertinoListTileType.notched when widget.leading != null => _kNotchedMinHeight,_CupertinoListTileType.base => _kMinHeight,_CupertinoListTileType.notched => _kNotchedMinHeightWithoutLeading,};final Widget child = Container(constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight),2 unmodified linespadding: padding,child: Row(children: <Widget>[if (widget.leading case final Widget leading) ...<Widget>[SizedBox.square(dimension: widget.leadingSize, child: Center(child: leading)),SizedBox(width: widget.leadingToTitle),] elseSizedBox(height: widget.leadingSize),3 unmodified linescrossAxisAlignment: CrossAxisAlignment.start,children: <Widget>[title,if (widget.subtitle case final Widget subtitle) ...<Widget>[const SizedBox(height: _kNotchedTitleToSubtitle),DefaultTextStyle(style: coloredStyle.copyWith(fontSize: baseType ? _kSubtitleFontSize : _kNotchedSubtitleFontSize,),maxLines: 1,overflow: TextOverflow.ellipsis,child: subtitle,),],],),),if (widget.additionalInfo case final Widget additionalInfo) ...<Widget>[DefaultTextStyle(style: coloredStyle, maxLines: 1, child: additionalInfo),if (widget.trailing != null) const SizedBox(width: _kAdditionalInfoToTrailing),],if (widget.trailing != null) widget.trailing!,],),),4 unmodified lines}return GestureDetector(onTapDown:(_) => setState(() {_tapped = true;}),onTapCancel:() => setState(() {_tapped = false;}),onTap: () async {await widget.onTap!();if (mounted) {setState(() {_tapped = false;});}},behavior: HitTestBehavior.opaque,
1 unmodified line2345679 unmodified lines17181920212223242526272829306 unmodified lines3738394041424344454647484950240 unmodified lines29129229329429529641 unmodified lines33833934034134234334433 unmodified lines3783793803813823833843856 unmodified lines39239339439539639739818 unmodified lines41741841942042142242342442542642742842943043143277 unmodified lines5105115125135145156 unmodified lines5225235245255261 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';9 unmodified lines////// Example: Fri Aug 31 | 02 | 08 | PM.date_time_dayPeriod,/// Order of the columns, from left to right: date, am/pm, hour, minute.////// Example: Fri Aug 31 | PM | 02 | 08.date_dayPeriod_time,/// Order of the columns, from left to right: hour, minute, am/pm, date.////// Example: 02 | 08 | PM | Fri Aug 31.time_dayPeriod_date,/// Order of the columns, from left to right: am/pm, hour, minute, date.////// Example: PM | 02 | 08 | Fri Aug 31.6 unmodified lines////// Example: 12 | March | 1996.dmy,/// Order of the columns, from left to right: month, day, year.////// Example: March | 12 | 1996.mdy,/// Order of the columns, from left to right: year, month, day.////// Example: 1996 | March | 12.ymd,/// Order of the columns, from left to right: year, day, month.////// Example: 1996 | 12 | March.240 unmodified lines/// indicate that a tap outside dismisses the context menu.String get menuDismissLabel;/// The `CupertinoLocalizations` from the closest [Localizations] instance/// that encloses the given context.///41 unmodified linesconst DefaultCupertinoLocalizations();/// Short version of days of week.static const List<String> shortWeekdays = <String>['Mon','Tue','Wed',33 unmodified lines'December',];@overrideString datePickerYear(int yearIndex) => yearIndex.toString();6 unmodified lines@overrideString datePickerDayOfMonth(int dayIndex, [int? weekDay]) {if (weekDay != null) {return ' ${shortWeekdays[weekDay - DateTime.monday]} $dayIndex ';}return dayIndex.toString();18 unmodified lines@overrideString datePickerMediumDate(DateTime date) {return '${shortWeekdays[date.weekday - DateTime.monday]} ''${_shortMonths[date.month - DateTime.january]} ''${date.day.toString().padRight(2)}';}@overrideDatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.mdy;@overrideDatePickerDateTimeOrder get datePickerDateTimeOrder => DatePickerDateTimeOrder.date_time_dayPeriod;@overrideString get anteMeridiemAbbreviation => 'AM';77 unmodified lines@overrideString get menuDismissLabel => 'Dismiss menu';/// Creates an object that provides US English resource values for the/// cupertino library widgets.///6 unmodified lines/// A [LocalizationsDelegate] that uses [DefaultCupertinoLocalizations.load]/// to create an instance of this class.static const LocalizationsDelegate<CupertinoLocalizations> delegate = _CupertinoLocalizationsDelegate();}1 unmodified line234567891011129 unmodified lines22232425262728293031323334353637386 unmodified lines4546474849505152535455565758596061240 unmodified lines30230330430530630730830931031131231341 unmodified lines35535635735835936036133 unmodified lines3953963973983994006 unmodified lines40740840941041141241318 unmodified lines43243343443543643743843944044144244344444544644744877 unmodified lines5265275285295305315325335345355365376 unmodified lines5445455465475485491 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'bottom_tab_bar.dart';/// @docImport 'date_picker.dart';/// @docImport 'search_field.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';9 unmodified lines////// Example: Fri Aug 31 | 02 | 08 | PM.date_time_dayPeriod,/// Order of the columns, from left to right: date, am/pm, hour, minute.////// Example: Fri Aug 31 | PM | 02 | 08.date_dayPeriod_time,/// Order of the columns, from left to right: hour, minute, am/pm, date.////// Example: 02 | 08 | PM | Fri Aug 31.time_dayPeriod_date,/// Order of the columns, from left to right: am/pm, hour, minute, date.////// Example: PM | 02 | 08 | Fri Aug 31.6 unmodified lines////// Example: 12 | March | 1996.dmy,/// Order of the columns, from left to right: month, day, year.////// Example: March | 12 | 1996.mdy,/// Order of the columns, from left to right: year, month, day.////// Example: 1996 | March | 12.ymd,/// Order of the columns, from left to right: year, day, month.////// Example: 1996 | 12 | March.240 unmodified lines/// indicate that a tap outside dismisses the context menu.String get menuDismissLabel;/// The label for the cancel button in modal views, used in [CupertinoNavigationBar] and [CupertinoSliverNavigationBar].String get cancelButtonLabel;/// The label for the back button, used in [CupertinoNavigationBar] and [CupertinoSliverNavigationBar].String get backButtonLabel;/// The `CupertinoLocalizations` from the closest [Localizations] instance/// that encloses the given context.///41 unmodified linesconst DefaultCupertinoLocalizations();/// Short version of days of week.static const List<String> _shortWeekdays = <String>['Mon','Tue','Wed',33 unmodified lines'December',];@overrideString datePickerYear(int yearIndex) => yearIndex.toString();6 unmodified lines@overrideString datePickerDayOfMonth(int dayIndex, [int? weekDay]) {if (weekDay != null) {return ' ${_shortWeekdays[weekDay - DateTime.monday]} $dayIndex ';}return dayIndex.toString();18 unmodified lines@overrideString datePickerMediumDate(DateTime date) {return '${_shortWeekdays[date.weekday - DateTime.monday]} ''${_shortMonths[date.month - DateTime.january]} ''${date.day.toString().padRight(2)}';}@overrideDatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.mdy;@overrideDatePickerDateTimeOrder get datePickerDateTimeOrder =>DatePickerDateTimeOrder.date_time_dayPeriod;@overrideString get anteMeridiemAbbreviation => 'AM';77 unmodified lines@overrideString get menuDismissLabel => 'Dismiss menu';@overrideString get cancelButtonLabel => 'Cancel';@overrideString get backButtonLabel => 'Back';/// Creates an object that provides US English resource values for the/// cupertino library widgets.///6 unmodified lines/// A [LocalizationsDelegate] that uses [DefaultCupertinoLocalizations.load]/// to create an instance of this class.static const LocalizationsDelegate<CupertinoLocalizations> delegate =_CupertinoLocalizationsDelegate();}
1 unmodified line234567891011121350 unmodified lines6465666768697071727374757677783 unmodified lines82838485868788895 unmodified lines959697989910010110210310410510610710810911011111211311411511611711813 unmodified lines13213313413513613713813914014114214314414514614714810 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082 unmodified lines2112122132142152162 unmodified lines2192202212222232249 unmodified lines2342352362372382392404 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722734 unmodified lines2782792802812822832842852866 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193203213221 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;import 'package:flutter/widgets.dart';/// A [CupertinoMagnifier] used for magnifying text in cases where a user's/// finger may be blocking the point of interest, like a selection handle.////// Delegates styling to [CupertinoMagnifier] with its position depending on/// [magnifierInfo].///50 unmodified lines/// [CupertinoTextMagnifier] will determine its own positioning/// based on the [MagnifierInfo] of this notifier.final ValueNotifier<MagnifierInfo>magnifierInfo;/// The duration that the magnifier drags behind its final position.static const Duration _kDragAnimationDuration = Duration(milliseconds: 45);@overrideState<CupertinoTextMagnifier> createState() =>_CupertinoTextMagnifierState();}class _CupertinoTextMagnifierState extends State<CupertinoTextMagnifier>3 unmodified lines// set these values.Offset _currentAdjustedMagnifierPosition = Offset.zero;double _verticalFocalPointAdjustment = 0;late AnimationController _ioAnimationController;late Animation<double> _ioAnimation;@overridevoid initState() {5 unmodified lines)..addListener(() => setState(() {}));widget.controller.animationController = _ioAnimationController;widget.magnifierInfo.addListener(_determineMagnifierPositionAndFocalPoint);_ioAnimation = Tween<double>(begin: 0.0,end: 1.0,).animate(CurvedAnimation(parent: _ioAnimationController,curve: widget.animationCurve,));}@overridevoid dispose() {widget.controller.animationController = null;_ioAnimationController.dispose();widget.magnifierInfo.removeListener(_determineMagnifierPositionAndFocalPoint);super.dispose();}13 unmodified lines}void _determineMagnifierPositionAndFocalPoint() {final MagnifierInfo textEditingContext =widget.magnifierInfo.value;// The exact Y of the center of the current line.final double verticalCenterOfCurrentLine =textEditingContext.caretRect.center.dy;// If the magnifier is currently showing, but we have dragged out of threshold,// we should hide it.if (verticalCenterOfCurrentLine -textEditingContext.globalGesturePosition.dy <-widget.hideBelowThreshold) {// Only signal a hide if we are currently showing.if (widget.controller.shown) {10 unmodified lines// Never go above the center of the line, but have some resistance// going downward if the drag goes too far.final double verticalPositionOfLens = math.max(verticalCenterOfCurrentLine,verticalCenterOfCurrentLine -(verticalCenterOfCurrentLine -textEditingContext.globalGesturePosition.dy) /widget.dragResistance);// The raw position, tracking the gesture directly.final Offset rawMagnifierPosition = Offset(textEditingContext.globalGesturePosition.dx -CupertinoMagnifier.kDefaultSize.width / 2,verticalPositionOfLens -(CupertinoMagnifier.kDefaultSize.height -CupertinoMagnifier.kMagnifierAboveFocalPoint),);final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context);// Adjust the magnifier position so that it never exists outside the horizontal// padding.final Offset adjustedMagnifierPosition = MagnifierController.shiftWithinBounds(bounds: Rect.fromLTRB(screenRect.left + widget.horizontalScreenEdgePadding,// iOS doesn't reposition for Y, so we should expand the threshold// so we can send the whole magnifier out of bounds if need be.screenRect.top -(CupertinoMagnifier.kDefaultSize.height +CupertinoMagnifier.kMagnifierAboveFocalPoint),screenRect.right - widget.horizontalScreenEdgePadding,screenRect.bottom +(CupertinoMagnifier.kDefaultSize.height +CupertinoMagnifier.kMagnifierAboveFocalPoint)),rect: rawMagnifierPosition & CupertinoMagnifier.kDefaultSize,).topLeft;setState(() {_currentAdjustedMagnifierPosition = adjustedMagnifierPosition;// The lens should always point to the center of the line._verticalFocalPointAdjustment =verticalCenterOfCurrentLine - verticalPositionOfLens;});}@overrideWidget build(BuildContext context) {return AnimatedPositioned(duration: CupertinoTextMagnifier._kDragAnimationDuration,curve: widget.animationCurve,2 unmodified lineschild: CupertinoMagnifier(inOutAnimation: _ioAnimation,additionalFocalPointOffset: Offset(0, _verticalFocalPointAdjustment),),);}2 unmodified lines/// A [RawMagnifier] used for magnifying text in cases where a user's/// finger may be blocking the point of interest, like a selection handle.////// [CupertinoMagnifier] is a wrapper around [RawMagnifier] that handles styling/// and transitions.///9 unmodified lines/// Creates a [RawMagnifier] in the Cupertino style.////// The default constructor parameters and constants were eyeballed on/// an iPhone XR iOS v15.5.const CupertinoMagnifier({super.key,this.size = kDefaultSize,4 unmodified linescolor: Color.fromARGB(25, 0, 0, 0),blurRadius: 11,spreadRadius: 0.2,),],this.borderSide =const BorderSide(color: Color.fromARGB(255, 232, 232, 232)),this.inOutAnimation,});/// The shadows displayed under the magnifier.final List<BoxShadow> shadows;/// The border, or "rim", of this magnifier.final BorderSide borderSide;/// The vertical offset that the magnifier is along the Y axis above/// the focal point.@visibleForTestingstatic const double kMagnifierAboveFocalPoint = -26;/// The default size of the magnifier.////// This is public so that positioners can choose to depend on it, although/// it is overridable.@visibleForTestingstatic const Size kDefaultSize = Size(80, 47.5);/// The duration that this magnifier animates in / out for.4 unmodified linesstatic const Duration _kInOutAnimationDuration = Duration(milliseconds: 150);/// The size of this magnifier.final Size size;/// The border radius of this magnifier.final BorderRadius borderRadius;/// This [RawMagnifier]'s controller.6 unmodified lines/// point offset defined in [kMagnifierAboveFocalPoint].final Offset additionalFocalPointOffset;@overrideWidget build(BuildContext context) {Offset focalPointOffset =Offset(0, (kDefaultSize.height / 2) - kMagnifierAboveFocalPoint);focalPointOffset.scale(1, inOutAnimation?.value ?? 1);focalPointOffset += additionalFocalPointOffset;return Transform.translate(offset: Offset.lerp(const Offset(0, -kMagnifierAboveFocalPoint),Offset.zero,inOutAnimation?.value ?? 1,)!,child: RawMagnifier(size: size,focalPointOffset: focalPointOffset,decoration: MagnifierDecoration(opacity: inOutAnimation?.value ?? 1,shape: RoundedRectangleBorder(borderRadius: borderRadius,side: borderSide,),shadows: shadows,),),);}1 unmodified line234567891011121314151617181920212223242550 unmodified lines767778798081828384858687883 unmodified lines92939495969798991005 unmodified lines10610710810911011111211311411511611711811912012112212312412513 unmodified lines13914014114214314414514614714814915015115210 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122 unmodified lines2152162172182192202212 unmodified lines2242252262272282292302312322332342359 unmodified lines2452462472482492502514 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143154 unmodified lines3203213223233243253263273283293303313326 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713721 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'dart:math' as math;import 'package:flutter/widgets.dart';import 'theme.dart';/// A [CupertinoMagnifier] used for magnifying text in cases where a user's/// finger may be blocking the point of interest, like a selection handle.////// {@tool dartpad}/// This sample demonstrates how to use [CupertinoTextMagnifier].////// ** See code in examples/api/lib/widgets/magnifier/cupertino_text_magnifier.0.dart **/// {@end-tool}////// Delegates styling to [CupertinoMagnifier] with its position depending on/// [magnifierInfo].///50 unmodified lines/// [CupertinoTextMagnifier] will determine its own positioning/// based on the [MagnifierInfo] of this notifier.final ValueNotifier<MagnifierInfo> magnifierInfo;/// The duration that the magnifier drags behind its final position.static const Duration _kDragAnimationDuration = Duration(milliseconds: 45);@overrideState<CupertinoTextMagnifier> createState() => _CupertinoTextMagnifierState();}class _CupertinoTextMagnifierState extends State<CupertinoTextMagnifier>3 unmodified lines// set these values.Offset _currentAdjustedMagnifierPosition = Offset.zero;double _verticalFocalPointAdjustment = 0;late final AnimationController _ioAnimationController;late final Animation<double> _ioAnimation;late final CurvedAnimation _ioCurvedAnimation;@overridevoid initState() {5 unmodified lines)..addListener(() => setState(() {}));widget.controller.animationController = _ioAnimationController;widget.magnifierInfo.addListener(_determineMagnifierPositionAndFocalPoint);_ioCurvedAnimation = CurvedAnimation(parent: _ioAnimationController,curve: widget.animationCurve,);_ioAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(_ioCurvedAnimation);}@overridevoid dispose() {widget.controller.animationController = null;_ioAnimationController.dispose();_ioCurvedAnimation.dispose();widget.magnifierInfo.removeListener(_determineMagnifierPositionAndFocalPoint);super.dispose();}13 unmodified lines}void _determineMagnifierPositionAndFocalPoint() {final MagnifierInfo textEditingContext = widget.magnifierInfo.value;// The exact Y of the center of the current line.final double verticalCenterOfCurrentLine = textEditingContext.caretRect.center.dy;// If the magnifier is currently showing, but we have dragged out of threshold,// we should hide it.if (verticalCenterOfCurrentLine - textEditingContext.globalGesturePosition.dy <-widget.hideBelowThreshold) {// Only signal a hide if we are currently showing.if (widget.controller.shown) {10 unmodified lines// Never go above the center of the line, but have some resistance// going downward if the drag goes too far.final double verticalPositionOfLens = math.max(verticalCenterOfCurrentLine,verticalCenterOfCurrentLine -(verticalCenterOfCurrentLine - textEditingContext.globalGesturePosition.dy) /widget.dragResistance,);// The raw position, tracking the gesture directly.final Offset rawMagnifierPosition = Offset(textEditingContext.globalGesturePosition.dx - CupertinoMagnifier.kDefaultSize.width / 2,verticalPositionOfLens -(CupertinoMagnifier.kDefaultSize.height - CupertinoMagnifier.kMagnifierAboveFocalPoint),);final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context);// Adjust the magnifier position so that it never exists outside the horizontal// padding.final Offset adjustedMagnifierPosition =MagnifierController.shiftWithinBounds(bounds: Rect.fromLTRB(screenRect.left + widget.horizontalScreenEdgePadding,// iOS doesn't reposition for Y, so we should expand the threshold// so we can send the whole magnifier out of bounds if need be.screenRect.top -(CupertinoMagnifier.kDefaultSize.height +CupertinoMagnifier.kMagnifierAboveFocalPoint),screenRect.right - widget.horizontalScreenEdgePadding,screenRect.bottom +(CupertinoMagnifier.kDefaultSize.height +CupertinoMagnifier.kMagnifierAboveFocalPoint),),rect: rawMagnifierPosition & CupertinoMagnifier.kDefaultSize,).topLeft;setState(() {_currentAdjustedMagnifierPosition = adjustedMagnifierPosition;// The lens should always point to the center of the line._verticalFocalPointAdjustment = verticalCenterOfCurrentLine - verticalPositionOfLens;});}@overrideWidget build(BuildContext context) {final CupertinoThemeData themeData = CupertinoTheme.of(context);return AnimatedPositioned(duration: CupertinoTextMagnifier._kDragAnimationDuration,curve: widget.animationCurve,2 unmodified lineschild: CupertinoMagnifier(inOutAnimation: _ioAnimation,additionalFocalPointOffset: Offset(0, _verticalFocalPointAdjustment),borderSide: BorderSide(color: themeData.primaryColor, width: 2.0),),);}2 unmodified lines/// A [RawMagnifier] used for magnifying text in cases where a user's/// finger may be blocking the point of interest, like a selection handle.////// {@tool dartpad}/// This sample demonstrates how to use [CupertinoMagnifier].////// ** See code in examples/api/lib/widgets/magnifier/cupertino_magnifier.0.dart **/// {@end-tool}////// [CupertinoMagnifier] is a wrapper around [RawMagnifier] that handles styling/// and transitions.///9 unmodified lines/// Creates a [RawMagnifier] in the Cupertino style.////// The default constructor parameters and constants were eyeballed on/// an iPhone 16 iOS v18.1.const CupertinoMagnifier({super.key,this.size = kDefaultSize,4 unmodified linescolor: Color.fromARGB(25, 0, 0, 0),blurRadius: 11,spreadRadius: 0.2,blurStyle: BlurStyle.outer,),],this.clipBehavior = Clip.none,this.borderSide = const BorderSide(color: Color.fromARGB(255, 0, 124, 255), width: 2.0),this.inOutAnimation,this.magnificationScale = 1.0,}) : assert(magnificationScale > 0, 'The magnification scale should be greater than zero.');/// A list of shadows cast by the [Magnifier].////// If the shadows use a [BlurStyle] that paints inside the shape, or if they/// are offset, then a [clipBehavior] that enables clipping (such as/// [Clip.hardEdge]) is recommended, otherwise the shadow will occlude the/// magnifier (the shadow is drawn above the magnifier so as to not be/// included in the magnified image).////// A shadow that uses [BlurStyle.outer] and is not offset does not need/// clipping.////// By default, the [shadows] are not offset and use [BlurStyle.outer], and/// correspondingly the default [clipBehavior] is [Clip.none].final List<BoxShadow> shadows;/// Whether and how to clip the [shadows] that render inside the loupe.////// Defaults to [Clip.none], which is useful if the shadow will not paint/// where the magnified image appears, or if doing so is intentional (e.g. to/// blur the edges of the magnified image).////// The default configuration of [CupertinoMagnifier] does not render inside/// the loupe (the shadows are not offset and use [BlurStyle.outer]).////// Other values (e.g. [Clip.hardEdge]) are recommended when the [shadows]/// have an offset.////// See the discussion at [shadows].final Clip clipBehavior;/// The border, or "rim", of this magnifier.////// This border is drawn on a [RoundedRectangleBorder] with radius/// [borderRadius], and increases the [size] of the magnifier by the/// [BorderSide.width].final BorderSide borderSide;/// The vertical offset that the magnifier is along the Y axis above/// the focal point.static const double kMagnifierAboveFocalPoint = -26;/// The default size of the magnifier.////// This is public so that positioners can choose to depend on it, although/// it is overridable.static const Size kDefaultSize = Size(80, 47.5);/// The duration that this magnifier animates in / out for.4 unmodified linesstatic const Duration _kInOutAnimationDuration = Duration(milliseconds: 150);/// The size of this magnifier.////// The size does not include the [borderSide] or [shadows].final Size size;/// The border radius of this magnifier.////// The magnifier's shape is a [RoundedRectangleBorder] with this radius.final BorderRadius borderRadius;/// This [RawMagnifier]'s controller.6 unmodified lines/// point offset defined in [kMagnifierAboveFocalPoint].final Offset additionalFocalPointOffset;/// The magnification scale for the magnifier.////// Defaults to 1.0, which indicates that the magnifier does not apply any magnification.final double magnificationScale;@overrideWidget build(BuildContext context) {Offset focalPointOffset = Offset(0, (kDefaultSize.height / 2) - kMagnifierAboveFocalPoint);focalPointOffset.scale(1, inOutAnimation?.value ?? 1);focalPointOffset += additionalFocalPointOffset;return Transform.translate(offset:Offset.lerp(const Offset(0, -kMagnifierAboveFocalPoint),Offset.zero,inOutAnimation?.value ?? 1,)!,child: RawMagnifier(size: size,focalPointOffset: focalPointOffset,decoration: MagnifierDecoration(opacity: inOutAnimation?.value ?? 1,shape: RoundedRectangleBorder(borderRadius: borderRadius, side: borderSide),shadows: shadows,),clipBehavior: clipBehavior,magnificationScale: magnificationScale,),);}
1 unmodified line23456711 unmodified lines1920212223242557 unmodified lines8384858687888911 unmodified lines1011021031041051062 unmodified lines1091101111121131141151161171181191201211221233 unmodified lines1271281291301311321331341351361372 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/widgets.dart';import 'colors.dart';11 unmodified lines/// a [ScrollView] to the enclosing [PrimaryScrollController].////// {@tool dartpad}/// This example shows a [CupertinoPageScaffold] with a [ListView] as a [child]./// The [CupertinoButton] is connected to a callback that increments a counter./// The [backgroundColor] can be changed.///57 unmodified lines}class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> {void _handleStatusBarTap() {final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);// Only act on the scroll controller if it has any attached scroll positions.11 unmodified linesWidget build(BuildContext context) {Widget paddedContent = widget.child;final MediaQueryData existingMediaQuery = MediaQuery.of(context);if (widget.navigationBar != null) {// TODO(xster): Use real size after partial layout instead of preferred size.2 unmodified lineswidget.navigationBar!.preferredSize.height + existingMediaQuery.padding.top;// Propagate bottom padding and include viewInsets if appropriatefinal double bottomPadding = widget.resizeToAvoidBottomInset? existingMediaQuery.viewInsets.bottom: 0.0;final EdgeInsets newViewInsets = widget.resizeToAvoidBottomInset// The insets are consumed by the scaffolds and no longer exposed to// the descendant subtree.? existingMediaQuery.viewInsets.copyWith(bottom: 0.0): existingMediaQuery.viewInsets;final bool fullObstruction = widget.navigationBar!.shouldFullyObstruct(context);3 unmodified linesif (fullObstruction) {paddedContent = MediaQuery(data: existingMediaQuery// If the navigation bar is opaque, the top media query padding is fully consumed by the navigation bar..removePadding(removeTop: true).copyWith(viewInsets: newViewInsets,),child: Padding(padding: EdgeInsets.only(top: topPadding, bottom: bottomPadding),child: paddedContent,2 unmodified lines} else {paddedContent = MediaQuery(data: existingMediaQuery.copyWith(padding: existingMediaQuery.padding.copyWith(top: topPadding,),viewInsets: newViewInsets,),child: Padding(padding: EdgeInsets.only(bottom: bottomPadding),child: paddedContent,),);}} else {// If there is no navigation bar, still may need to add padding in order// to support resizeToAvoidBottomInset.final double bottomPadding = widget.resizeToAvoidBottomInset? existingMediaQuery.viewInsets.bottom: 0.0;paddedContent = Padding(padding: EdgeInsets.only(bottom: bottomPadding),child: paddedContent,);}return DecoratedBox(decoration: BoxDecoration(color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context)?? CupertinoTheme.of(context).scaffoldBackgroundColor,),child: Stack(children: <Widget>[// The main content being at the bottom is added to the stack first.paddedContent,if (widget.navigationBar != null)Positioned(top: 0.0,left: 0.0,right: 0.0,child: MediaQuery.withNoTextScaling(child: widget.navigationBar!,),),// Add a touch handler the size of the status bar on top of all contents// to handle scroll to top by status bar taps.Positioned(top: 0.0,left: 0.0,right: 0.0,height: existingMediaQuery.padding.top,child: GestureDetector(excludeFromSemantics: true,onTap: _handleStatusBarTap,),),],),);}}/// Widget that has a preferred size and reports whether it fully obstructs/// widgets behind it.///1 unmodified line23456789101112131411 unmodified lines2627282930313257 unmodified lines90919293949511 unmodified lines1071081091101111121131141151162 unmodified lines1191201211221231241251261271281291301311321333 unmodified lines1371381391401411421431441452 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392401 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'button.dart';/// @docImport 'nav_bar.dart';/// @docImport 'route.dart';/// @docImport 'tab_scaffold.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';11 unmodified lines/// a [ScrollView] to the enclosing [PrimaryScrollController].////// {@tool dartpad}/// This example shows a [CupertinoPageScaffold] with a [Center] as a [child]./// The [CupertinoButton] is connected to a callback that increments a counter./// The [backgroundColor] can be changed.///57 unmodified lines}class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> {void _handleStatusBarTap() {final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);// Only act on the scroll controller if it has any attached scroll positions.11 unmodified linesWidget build(BuildContext context) {Widget paddedContent = widget.child;final Color backgroundColor =CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ??CupertinoTheme.of(context).scaffoldBackgroundColor;final MediaQueryData existingMediaQuery = MediaQuery.of(context);if (widget.navigationBar != null) {// TODO(xster): Use real size after partial layout instead of preferred size.2 unmodified lineswidget.navigationBar!.preferredSize.height + existingMediaQuery.padding.top;// Propagate bottom padding and include viewInsets if appropriatefinal double bottomPadding =widget.resizeToAvoidBottomInset ? existingMediaQuery.viewInsets.bottom : 0.0;final EdgeInsets newViewInsets =widget.resizeToAvoidBottomInset// The insets are consumed by the scaffolds and no longer exposed to// the descendant subtree.? existingMediaQuery.viewInsets.copyWith(bottom: 0.0): existingMediaQuery.viewInsets;final bool fullObstruction = widget.navigationBar!.shouldFullyObstruct(context);3 unmodified linesif (fullObstruction) {paddedContent = MediaQuery(data: existingMediaQuery// If the navigation bar is opaque, the top media query padding is fully consumed by the navigation bar..removePadding(removeTop: true).copyWith(viewInsets: newViewInsets),child: Padding(padding: EdgeInsets.only(top: topPadding, bottom: bottomPadding),child: paddedContent,2 unmodified lines} else {paddedContent = MediaQuery(data: existingMediaQuery.copyWith(padding: existingMediaQuery.padding.copyWith(top: topPadding),viewInsets: newViewInsets,),child: Padding(padding: EdgeInsets.only(bottom: bottomPadding), child: paddedContent),);}} else if (widget.resizeToAvoidBottomInset) {// If there is no navigation bar, still may need to add padding in order// to support resizeToAvoidBottomInset.paddedContent = MediaQuery(data: existingMediaQuery.copyWith(viewInsets: existingMediaQuery.viewInsets.copyWith(bottom: 0),),child: Padding(padding: EdgeInsets.only(bottom: existingMediaQuery.viewInsets.bottom),child: paddedContent,),);}return ScrollNotificationObserver(child: DecoratedBox(decoration: BoxDecoration(color: backgroundColor),child: CupertinoPageScaffoldBackgroundColor(color: backgroundColor,child: Stack(children: <Widget>[// The main content being at the bottom is added to the stack first.paddedContent,if (widget.navigationBar != null)Positioned(top: 0.0,left: 0.0,right: 0.0,child: MediaQuery.withNoTextScaling(child: widget.navigationBar!),),// Add a touch handler the size of the status bar on top of all contents// to handle scroll to top by status bar taps.Positioned(top: 0.0,left: 0.0,right: 0.0,height: existingMediaQuery.padding.top,child: GestureDetector(excludeFromSemantics: true, onTap: _handleStatusBarTap),),],),),),);}}/// [InheritedWidget] indicating what the current scaffold background color is for its children.////// This is used by the [CupertinoNavigationBar] and the [CupertinoSliverNavigationBar] widgets/// to paint themselves with the parent page scaffold color when no content is scrolled under.class CupertinoPageScaffoldBackgroundColor extends InheritedWidget {/// Constructs a new [CupertinoPageScaffoldBackgroundColor].const CupertinoPageScaffoldBackgroundColor({required super.child,required this.color,super.key,});/// The background color defined in [CupertinoPageScaffold].final Color color;@overridebool updateShouldNotify(CupertinoPageScaffoldBackgroundColor oldWidget) {return color != oldWidget.color;}/// Retrieve the [CupertinoPageScaffold] background color from the context.static Color? maybeOf(BuildContext context) {final CupertinoPageScaffoldBackgroundColor? scaffoldBackgroundColor =context.dependOnInheritedWidgetOfExactType<CupertinoPageScaffoldBackgroundColor>();return scaffoldBackgroundColor?.color;}@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {super.debugFillProperties(properties);properties.add(ColorProperty('page scaffold background color', color));}}/// Widget that has a preferred size and reports whether it fully obstructs/// widgets behind it.///
1 unmodified line234567811 unmodified lines20212223242560 unmodified lines868788899091929394159 unmodified lines2542552562572582591 unmodified line2612622632642652662672682693 unmodified lines2732742752762772782792802812822832842852862872882892903 unmodified lines29429529629729829930030130230330430530630730830931031131231315 unmodified lines32933033133233333433558 unmodified lines3943953963973983994004014024034 unmodified lines40840941041141241341451 unmodified lines4664674684694704712 unmodified lines47447547647747847948027 unmodified lines5085095101 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';11 unmodified lines// lens.const double _kOverAndUnderCenterOpacity = 0.447;/// An iOS-styled picker.////// Displays its children widgets on a wheel for selection and60 unmodified linesassert(magnification > 0),assert(itemExtent > 0),assert(squeeze > 0),childDelegate = looping? ListWheelChildLoopingListDelegate(children: children): ListWheelChildListDelegate(children: children);/// Creates a picker from an [IndexedWidgetBuilder] callback where the builder/// is dynamically invoked during layout.159 unmodified lineswidget.onSelectedItemChanged?.call(index);}/// Draws the selectionOverlay.Widget _buildSelectionOverlay(Widget selectionOverlay) {final double height = widget.itemExtent * widget.magnification;1 unmodified linereturn IgnorePointer(child: Center(child: ConstrainedBox(constraints: BoxConstraints.expand(height: height,),child: selectionOverlay,),),3 unmodified lines@overrideWidget build(BuildContext context) {final TextStyle textStyle = CupertinoTheme.of(context).textTheme.pickerTextStyle;final Color? resolvedBackgroundColor = CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context);assert(RenderListWheelViewport.defaultPerspective == _kDefaultPerspective);final Widget result = DefaultTextStyle(style: textStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(textStyle.color, context)),child: Stack(children: <Widget>[Positioned.fill(child: _CupertinoPickerSemantics(scrollController: widget.scrollController ?? _controller!,child: ListWheelScrollView.useDelegate(controller: widget.scrollController ?? _controller,physics: const FixedExtentScrollPhysics(),diameterRatio: widget.diameterRatio,offAxisFraction: widget.offAxisFraction,3 unmodified linesitemExtent: widget.itemExtent,squeeze: widget.squeeze,onSelectedItemChanged: _handleSelectedItemChanged,childDelegate: widget.childDelegate,),),),if (widget.selectionOverlay != null)_buildSelectionOverlay(widget.selectionOverlay!),],),);return DecoratedBox(decoration: BoxDecoration(color: resolvedBackgroundColor),child: result,);}}15 unmodified lines////// * [CupertinoPicker], which uses this widget as its default [CupertinoPicker.selectionOverlay].class CupertinoPickerDefaultSelectionOverlay extends StatelessWidget {/// Creates an iOS 14 style selection overlay that highlights the magnified/// area (or the currently selected item, depending on how you described it/// elsewhere) of a [CupertinoPicker].58 unmodified lines// adjustable semantic node, with adjustment callbacks wired to move the// scroll controller.class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget {const _CupertinoPickerSemantics({super.child,required this.scrollController,});final FixedExtentScrollController scrollController;4 unmodified lines}@overridevoid updateRenderObject(BuildContext context, covariant _RenderCupertinoPickerSemantics renderObject) {assert(debugCheckHasDirectionality(context));renderObject..textDirection = Directionality.of(context)51 unmodified lines_currentIndex = controller.selectedItem;markNeedsSemanticsUpdate();}@overridevoid describeSemanticsConfiguration(SemanticsConfiguration config) {super.describeSemanticsConfiguration(config);2 unmodified lines}@overridevoid assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {if (children.isEmpty) {return super.assembleSemanticsNode(node, config, children);}27 unmodified linescontroller.removeListener(_handleScrollUpdate);}}1 unmodified line234567891011121311 unmodified lines2526272829303132333435363760 unmodified lines9899100101102103104105106107159 unmodified lines2672682692702712722732742752762772782792801 unmodified line2822832842852862872883 unmodified lines2922932942952962972982993003013023033043053063073083093103113123133143153 unmodified lines31932032132232332432532632732832933033133233333433533633733815 unmodified lines35435535635735835958 unmodified lines4184194204214224234244 unmodified lines42943043143243343443543643743851 unmodified lines4904914924934944954962 unmodified lines49950050150250350450550650750850927 unmodified lines5375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685691 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'route.dart';/// @docImport 'text_theme.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';11 unmodified lines// lens.const double _kOverAndUnderCenterOpacity = 0.447;// The duration and curve of the tap-to-scroll gesture's animation when a picker// item is tapped.//// Eyeballed from an iPhone 15 Pro simulator running iOS 17.5.const Duration _kCupertinoPickerTapToScrollDuration = Duration(milliseconds: 300);const Curve _kCupertinoPickerTapToScrollCurve = Curves.easeInOut;/// An iOS-styled picker.////// Displays its children widgets on a wheel for selection and60 unmodified linesassert(magnification > 0),assert(itemExtent > 0),assert(squeeze > 0),childDelegate =looping? ListWheelChildLoopingListDelegate(children: children): ListWheelChildListDelegate(children: children);/// Creates a picker from an [IndexedWidgetBuilder] callback where the builder/// is dynamically invoked during layout.159 unmodified lineswidget.onSelectedItemChanged?.call(index);}void _handleChildTap(int index, FixedExtentScrollController controller) {controller.animateToItem(index,duration: _kCupertinoPickerTapToScrollDuration,curve: _kCupertinoPickerTapToScrollCurve,);}/// Draws the selectionOverlay.Widget _buildSelectionOverlay(Widget selectionOverlay) {final double height = widget.itemExtent * widget.magnification;1 unmodified linereturn IgnorePointer(child: Center(child: ConstrainedBox(constraints: BoxConstraints.expand(height: height),child: selectionOverlay,),),3 unmodified lines@overrideWidget build(BuildContext context) {final TextStyle textStyle = CupertinoTheme.of(context).textTheme.pickerTextStyle;final Color? resolvedBackgroundColor = CupertinoDynamicColor.maybeResolve(widget.backgroundColor,context,);assert(RenderListWheelViewport.defaultPerspective == _kDefaultPerspective);final FixedExtentScrollController controller = widget.scrollController ?? _controller!;final Widget result = DefaultTextStyle(style: textStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(textStyle.color, context),),child: Stack(children: <Widget>[Positioned.fill(child: _CupertinoPickerSemantics(scrollController: controller,child: ListWheelScrollView.useDelegate(controller: controller,physics: const FixedExtentScrollPhysics(),diameterRatio: widget.diameterRatio,offAxisFraction: widget.offAxisFraction,3 unmodified linesitemExtent: widget.itemExtent,squeeze: widget.squeeze,onSelectedItemChanged: _handleSelectedItemChanged,dragStartBehavior: DragStartBehavior.down,childDelegate: _CupertinoPickerListWheelChildDelegateWrapper(widget.childDelegate,onTappedChild: (int index) => _handleChildTap(index, controller),),),),),if (widget.selectionOverlay != null) _buildSelectionOverlay(widget.selectionOverlay!),],),);return DecoratedBox(decoration: BoxDecoration(color: resolvedBackgroundColor), child: result);}}15 unmodified lines////// * [CupertinoPicker], which uses this widget as its default [CupertinoPicker.selectionOverlay].class CupertinoPickerDefaultSelectionOverlay extends StatelessWidget {/// Creates an iOS 14 style selection overlay that highlights the magnified/// area (or the currently selected item, depending on how you described it/// elsewhere) of a [CupertinoPicker].58 unmodified lines// adjustable semantic node, with adjustment callbacks wired to move the// scroll controller.class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget {const _CupertinoPickerSemantics({super.child, required this.scrollController});final FixedExtentScrollController scrollController;4 unmodified lines}@overridevoid updateRenderObject(BuildContext context,covariant _RenderCupertinoPickerSemantics renderObject,) {assert(debugCheckHasDirectionality(context));renderObject..textDirection = Directionality.of(context)51 unmodified lines_currentIndex = controller.selectedItem;markNeedsSemanticsUpdate();}@overridevoid describeSemanticsConfiguration(SemanticsConfiguration config) {super.describeSemanticsConfiguration(config);2 unmodified lines}@overridevoid assembleSemanticsNode(SemanticsNode node,SemanticsConfiguration config,Iterable<SemanticsNode> children,) {if (children.isEmpty) {return super.assembleSemanticsNode(node, config, children);}27 unmodified linescontroller.removeListener(_handleScrollUpdate);}}class _CupertinoPickerListWheelChildDelegateWrapper implements ListWheelChildDelegate {_CupertinoPickerListWheelChildDelegateWrapper(this._wrapped, {required this.onTappedChild});final ListWheelChildDelegate _wrapped;final void Function(int index) onTappedChild;@overrideWidget? build(BuildContext context, int index) {final Widget? child = _wrapped.build(context, index);if (child == null) {return child;}return GestureDetector(behavior: HitTestBehavior.translucent,excludeFromSemantics: true,onTap: () => onTappedChild(index),child: child,);}@overrideint? get estimatedChildCount => _wrapped.estimatedChildCount;@overridebool shouldRebuild(covariant _CupertinoPickerListWheelChildDelegateWrapper oldDelegate) =>_wrapped.shouldRebuild(oldDelegate._wrapped);@overrideint trueIndexOf(int index) => _wrapped.trueIndexOf(index);}
1 unmodified line234567891011125 unmodified lines181920212223242526272843 unmodified lines72737475767744 unmodified lines12212312412512612757 unmodified lines18518618718818919019129 unmodified lines22122222322422522622722822923023123223323423523623723823924024124224324414 unmodified lines25926026126226326426526626726826927027127227327427527627730 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293303313323335 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603613623633643651 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'toggleable.dart';// Examples can assume:// late BuildContext context;5 unmodified linesconst double _kOuterRadius = 7.0;const double _kInnerRadius = 2.975;// The relative values needed to transform a color to its equivalent focus// outline color.const double _kCupertinoFocusColorOpacity = 0.80;const double _kCupertinoFocusColorBrightness = 0.69;const double _kCupertinoFocusColorSaturation = 0.835;/// A macOS-style radio button.///43 unmodified linesrequired this.value,required this.groupValue,required this.onChanged,this.toggleable = false,this.activeColor,this.inactiveColor,44 unmodified lines/// ```final ValueChanged<T?>? onChanged;/// Set to true if this radio button is allowed to be returned to an/// indeterminate state by selecting it again when selected.///57 unmodified linesState<CupertinoRadio<T>> createState() => _CupertinoRadioState<T>();}class _CupertinoRadioState<T> extends State<CupertinoRadio<T>> with TickerProviderStateMixin, ToggleableStateMixin {final _RadioPainter _painter = _RadioPainter();bool focused = false;29 unmodified lines}}@overrideWidget build(BuildContext context) {final Color effectiveActiveColor = widget.activeColor?? CupertinoColors.activeBlue;final Color effectiveInactiveColor = widget.inactiveColor?? CupertinoColors.white;final Color effectiveFocusOverlayColor = widget.focusColor?? HSLColor.fromColor(effectiveActiveColor.withOpacity(_kCupertinoFocusColorOpacity)).withLightness(_kCupertinoFocusColorBrightness).withSaturation(_kCupertinoFocusColorSaturation).toColor();final Color effectiveActivePressedOverlayColor =HSLColor.fromColor(effectiveActiveColor).withLightness(0.45).toColor();final Color effectiveFillColor = widget.fillColor ?? CupertinoColors.white;final bool? accessibilitySelected;// Apple devices also use `selected` to annotate radio button's semantics14 unmodified lineschecked: widget._selected,selected: accessibilitySelected,child: buildToggleable(focusNode: widget.focusNode,autofocus: widget.autofocus,onFocusChange: onFocusChange,size: _size,painter: _painter..focusColor = effectiveFocusOverlayColor..downPosition = downPosition..isFocused = focused..activeColor = downPosition != null ? effectiveActivePressedOverlayColor : effectiveActiveColor..inactiveColor = effectiveInactiveColor..fillColor = effectiveFillColor..value = value..checkmarkStyle = widget.useCheckmarkStyle,),);}30 unmodified linesnotifyListeners();}@overridevoid paint(Canvas canvas, Size size) {final Offset center = (Offset.zero & size).center;final Paint paint = Paint()..color = inactiveColor..style = PaintingStyle.fill..strokeWidth = 0.1;if (checkmarkStyle) {if (value ?? false) {final Path path = Path();final Paint checkPaint = Paint()..color = activeColor..style = PaintingStyle.stroke..strokeWidth = 2..strokeCap = StrokeCap.round;final double width = _size.width;final Offset origin = Offset(center.dx - (width/2), center.dy - (width/2));final Offset start = Offset(width * 0.25, width * 0.52);final Offset mid = Offset(width * 0.46, width * 0.75);final Offset end = Offset(width * 0.85, width * 0.29);5 unmodified linescanvas.drawPath(path, checkPaint);}} else {// Outer bordercanvas.drawCircle(center, _kOuterRadius, paint);paint.style = PaintingStyle.stroke;paint.color = CupertinoColors.inactiveGray;canvas.drawCircle(center, _kOuterRadius, paint);if (value ?? false) {paint.style = PaintingStyle.fill;paint.color = activeColor;canvas.drawCircle(center, _kOuterRadius, paint);paint.color = fillColor;canvas.drawCircle(center, _kInnerRadius, paint);}}if (isFocused) {paint.style = PaintingStyle.stroke;paint.color = focusColor;paint.strokeWidth = 3.0;canvas.drawCircle(center, _kOuterRadius + 1.5, paint);}}}1 unmodified line2345678910111213141516171819205 unmodified lines26272829303132333435363738394041424344454647484950515253545556575859606143 unmodified lines10510610710810911011144 unmodified lines15615715815916016116216316416516616716816917017117217317417517617717817918018118218357 unmodified lines24124224324424524624724829 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335414 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139239339430 unmodified lines4254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015 unmodified lines5075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715721 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'checkbox.dart';/// @docImport 'slider.dart';/// @docImport 'switch.dart';library;import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';import 'colors.dart';import 'constants.dart';import 'theme.dart';// Examples can assume:// late BuildContext context;5 unmodified linesconst double _kOuterRadius = 7.0;const double _kInnerRadius = 2.975;// Eyeballed from a radio on a physical Macbook Pro running macOS version 14.5.final Color _kDisabledOuterColor = CupertinoColors.white.withOpacity(0.50);const Color _kDisabledInnerColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(64, 0, 0, 0),darkColor: Color.fromARGB(64, 255, 255, 255),);const Color _kDisabledBorderColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(64, 0, 0, 0),darkColor: Color.fromARGB(64, 0, 0, 0),);const CupertinoDynamicColor _kDefaultBorderColor = CupertinoDynamicColor.withBrightness(color: Color.fromARGB(255, 209, 209, 214),darkColor: Color.fromARGB(64, 0, 0, 0),);const CupertinoDynamicColor _kDefaultInnerColor = CupertinoDynamicColor.withBrightness(color: CupertinoColors.white,darkColor: Color.fromARGB(255, 222, 232, 248),);const CupertinoDynamicColor _kDefaultOuterColor = CupertinoDynamicColor.withBrightness(color: CupertinoColors.activeBlue,darkColor: Color.fromARGB(255, 50, 100, 215),);const double _kPressedOverlayOpacity = 0.15;const double _kCheckmarkStrokeWidth = 2.0;const double _kFocusOutlineStrokeWidth = 3.0;const double _kBorderOutlineStrokeWidth = 0.3;// In dark mode, the outer color of a radio is an opacity gradient of the// background color.const List<double> _kDarkGradientOpacities = <double>[0.14, 0.29];const List<double> _kDisabledDarkGradientOpacities = <double>[0.08, 0.14];/// A macOS-style radio button.///43 unmodified linesrequired this.value,required this.groupValue,required this.onChanged,this.mouseCursor,this.toggleable = false,this.activeColor,this.inactiveColor,44 unmodified lines/// ```final ValueChanged<T?>? onChanged;/// The cursor for a mouse pointer when it enters or is hovering over the/// widget.////// If [mouseCursor] is a [WidgetStateMouseCursor],/// [WidgetStateMouseCursor.resolve] is used for the following [WidgetState]s:////// * [WidgetState.selected]./// * [WidgetState.hovered]./// * [WidgetState.focused]./// * [WidgetState.disabled].////// If null, then [SystemMouseCursors.basic] is used when this radio button is disabled./// When this radio button is enabled, [SystemMouseCursors.click] is used on Web, and/// [SystemMouseCursors.basic] is used on other platforms.////// See also:////// * [WidgetStateMouseCursor], a [MouseCursor] that implements/// `WidgetStateProperty` which is used in APIs that need to accept/// either a [MouseCursor] or a [WidgetStateProperty<MouseCursor>].final MouseCursor? mouseCursor;/// Set to true if this radio button is allowed to be returned to an/// indeterminate state by selecting it again when selected.///57 unmodified linesState<CupertinoRadio<T>> createState() => _CupertinoRadioState<T>();}class _CupertinoRadioState<T> extends State<CupertinoRadio<T>>with TickerProviderStateMixin, ToggleableStateMixin {final _RadioPainter _painter = _RadioPainter();bool focused = false;29 unmodified lines}}WidgetStateProperty<Color> get _defaultOuterColor {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if (states.contains(WidgetState.disabled)) {return CupertinoDynamicColor.resolve(_kDisabledOuterColor, context);}if (states.contains(WidgetState.selected)) {return widget.activeColor ?? CupertinoDynamicColor.resolve(_kDefaultOuterColor, context);}return widget.inactiveColor ?? CupertinoColors.white;});}WidgetStateProperty<Color> get _defaultInnerColor {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if (states.contains(WidgetState.disabled) && states.contains(WidgetState.selected)) {return widget.fillColor ?? CupertinoDynamicColor.resolve(_kDisabledInnerColor, context);}if (states.contains(WidgetState.selected)) {return widget.fillColor ?? CupertinoDynamicColor.resolve(_kDefaultInnerColor, context);}return CupertinoColors.white;});}WidgetStateProperty<Color> get _defaultBorderColor {return WidgetStateProperty.resolveWith((Set<WidgetState> states) {if ((states.contains(WidgetState.selected) || states.contains(WidgetState.focused)) &&!states.contains(WidgetState.disabled)) {return CupertinoColors.transparent;}if (states.contains(WidgetState.disabled)) {return CupertinoDynamicColor.resolve(_kDisabledBorderColor, context);}return CupertinoDynamicColor.resolve(_kDefaultBorderColor, context);});}@overrideWidget build(BuildContext context) {// Colors need to be resolved in selected and non selected states separately.final Set<WidgetState> activeStates = states..add(WidgetState.selected);final Set<WidgetState> inactiveStates = states..remove(WidgetState.selected);// Since the states getter always makes a new set, make a copy to use// throughout the lifecycle of this build method.final Set<WidgetState> currentStates = states;final Color effectiveActiveColor = _defaultOuterColor.resolve(activeStates);final Color effectiveInactiveColor = _defaultOuterColor.resolve(inactiveStates);final Color effectiveFocusOverlayColor =widget.focusColor ??HSLColor.fromColor(effectiveActiveColor.withOpacity(kCupertinoFocusColorOpacity)).withLightness(kCupertinoFocusColorBrightness).withSaturation(kCupertinoFocusColorSaturation).toColor();final Color effectiveFillColor = _defaultInnerColor.resolve(currentStates);final Color effectiveBorderColor = _defaultBorderColor.resolve(currentStates);final WidgetStateProperty<MouseCursor> effectiveMouseCursor =WidgetStateProperty.resolveWith<MouseCursor>((Set<WidgetState> states) {return WidgetStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states) ??(states.contains(WidgetState.disabled)? SystemMouseCursors.basic: kIsWeb? SystemMouseCursors.click: SystemMouseCursors.basic);});final bool? accessibilitySelected;// Apple devices also use `selected` to annotate radio button's semantics14 unmodified lineschecked: widget._selected,selected: accessibilitySelected,child: buildToggleable(mouseCursor: effectiveMouseCursor,focusNode: widget.focusNode,autofocus: widget.autofocus,onFocusChange: onFocusChange,size: _size,painter:_painter..position = position..reaction = reaction..focusColor = effectiveFocusOverlayColor..downPosition = downPosition..isFocused = focused..activeColor = effectiveActiveColor..inactiveColor = effectiveInactiveColor..fillColor = effectiveFillColor..value = value..checkmarkStyle = widget.useCheckmarkStyle..isActive = widget.onChanged != null..borderColor = effectiveBorderColor..brightness = CupertinoTheme.of(context).brightness,),);}30 unmodified linesnotifyListeners();}Brightness? get brightness => _brightness;Brightness? _brightness;set brightness(Brightness? value) {if (_brightness == value) {return;}_brightness = value;notifyListeners();}Color get borderColor => _borderColor!;Color? _borderColor;set borderColor(Color value) {if (_borderColor == value) {return;}_borderColor = value;notifyListeners();}void _drawPressedOverlay(Canvas canvas, Offset center, double radius) {final Paint pressedPaint =Paint()..color =brightness == Brightness.light? CupertinoColors.black.withOpacity(_kPressedOverlayOpacity): CupertinoColors.white.withOpacity(_kPressedOverlayOpacity);canvas.drawCircle(center, radius, pressedPaint);}void _drawFillGradient(Canvas canvas,Offset center,double radius,Color topColor,Color bottomColor,) {final LinearGradient fillGradient = LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,colors: <Color>[topColor, bottomColor],);final Rect circleRect = Rect.fromCircle(center: center, radius: radius);final Paint gradientPaint = Paint()..shader = fillGradient.createShader(circleRect);canvas.drawPath(Path()..addOval(circleRect), gradientPaint);}void _drawOuterBorder(Canvas canvas, Offset center) {final Paint borderPaint =Paint()..style = PaintingStyle.stroke..color = borderColor..strokeWidth = _kBorderOutlineStrokeWidth;canvas.drawCircle(center, _kOuterRadius, borderPaint);}@overridevoid paint(Canvas canvas, Size size) {final Offset center = (Offset.zero & size).center;if (checkmarkStyle) {if (value ?? false) {final Path path = Path();final Paint checkPaint =Paint()..color = activeColor..style = PaintingStyle.stroke..strokeWidth = _kCheckmarkStrokeWidth..strokeCap = StrokeCap.round;final double width = _size.width;final Offset origin = Offset(center.dx - (width / 2), center.dy - (width / 2));final Offset start = Offset(width * 0.25, width * 0.52);final Offset mid = Offset(width * 0.46, width * 0.75);final Offset end = Offset(width * 0.85, width * 0.29);5 unmodified linescanvas.drawPath(path, checkPaint);}} else {if (value ?? false) {final Paint outerPaint = Paint()..color = activeColor;// Draw a gradient in dark mode if the radio is disabled.if (brightness == Brightness.dark && !isActive) {_drawFillGradient(canvas,center,_kOuterRadius,outerPaint.color.withOpacity(isActive ? _kDarkGradientOpacities[0] : _kDisabledDarkGradientOpacities[0],),outerPaint.color.withOpacity(isActive ? _kDarkGradientOpacities[1] : _kDisabledDarkGradientOpacities[1],),);} else {canvas.drawCircle(center, _kOuterRadius, outerPaint);}// The outer circle's opacity changes when the radio is pressed.if (downPosition != null) {_drawPressedOverlay(canvas, center, _kOuterRadius);}final Paint innerPaint = Paint()..color = fillColor;canvas.drawCircle(center, _kInnerRadius, innerPaint);// Draw an outer border if the radio is disabled and selected.if (!isActive) {_drawOuterBorder(canvas, center);}} else {final Paint paint = Paint();paint.color = isActive ? inactiveColor : _kDisabledOuterColor;if (brightness == Brightness.dark) {_drawFillGradient(canvas,center,_kOuterRadius,paint.color.withOpacity(isActive ? _kDarkGradientOpacities[0] : _kDisabledDarkGradientOpacities[0],),paint.color.withOpacity(isActive ? _kDarkGradientOpacities[1] : _kDisabledDarkGradientOpacities[1],),);} else {canvas.drawCircle(center, _kOuterRadius, paint);}// The entire circle's opacity changes when the radio is pressed.if (downPosition != null) {_drawPressedOverlay(canvas, center, _kOuterRadius);}_drawOuterBorder(canvas, center);}}if (isFocused) {final Paint focusPaint =Paint()..style = PaintingStyle.stroke..color = focusColor..strokeWidth = _kFocusOutlineStrokeWidth;canvas.drawCircle(center, _kOuterRadius + _kFocusOutlineStrokeWidth / 2, focusPaint);}}}
1 unmodified line23456732 unmodified lines4041424344454658 unmodified lines10510610710810911011111210 unmodified lines1231241251261271281291301311321331341351361371381399 unmodified lines1491501511521531541551561571584 unmodified lines1631641651661671681691701 unmodified line17217317417517617717828 unmodified lines207208209210211212213214215216217218219132 unmodified lines35235335435535635735811 unmodified lines37037137237337437537610 unmodified lines3873883893903913923933943953963973983994002 unmodified lines40340440540640740840976 unmodified lines48648748848949049149249349449549649749849950050156 unmodified lines5585595605615625635641 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math';import 'package:flutter/foundation.dart' show clampDouble;32 unmodified lines}@overridevoid updateRenderObject(BuildContext context, covariant _RenderCupertinoSliverRefresh renderObject) {renderObject..refreshIndicatorLayoutExtent = refreshIndicatorLayoutExtent..hasLayoutExtent = hasLayoutExtent;58 unmodified linesassert(constraints.growthDirection == GrowthDirection.forward);// The new layout extent this sliver should now have.final double layoutExtent =(_hasLayoutExtent ? 1.0 : 0.0) * _refreshIndicatorExtent;// If the new layoutExtent instructive changed, the SliverGeometry's// layoutExtent will take that value (on the next performLayout run). Shift// the scroll offset first so it doesn't make the scroll position suddenly jump.10 unmodified lines}final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0;final double overscrolledExtent =constraints.overlap < 0.0 ? constraints.overlap.abs() : 0.0;// Layout the child giving it the space of the currently dragged overscroll// which may or may not include a sliver layout extent space that it will// keep after the user lets go during the refresh process.child!.layout(constraints.asBoxConstraints(maxExtent: layoutExtent// Plus only the overscrolled portion immediately preceding this// sliver.+ overscrolledExtent,),parentUsesSize: true,);9 unmodified linesmax(child!.size.height, layoutExtent) - constraints.scrollOffset,0.0,),maxPaintExtent: max(max(child!.size.height, layoutExtent) - constraints.scrollOffset,0.0,),layoutExtent: max(layoutExtent - constraints.scrollOffset, 0.0),);} else {4 unmodified lines@overridevoid paint(PaintingContext paintContext, Offset offset) {if (constraints.overlap < 0.0 ||constraints.scrollOffset + child!.size.height > 0) {paintContext.paintChild(child!, offset);}}1 unmodified line// Nothing special done here because this sliver always paints its child// exactly between paintOrigin and paintExtent.@overridevoid applyPaintTransform(RenderObject child, Matrix4 transform) { }}/// The current state of the refresh control.28 unmodified lines////// The `pulledExtent` parameter is the currently available space either from/// overscrolling or as held by the sliver during refresh.typedef RefreshControlIndicatorBuilder = Widget Function(BuildContext context,RefreshIndicatorMode refreshState,double pulledExtent,double refreshTriggerPullDistance,double refreshIndicatorExtent,);/// A callback function that's invoked when the [CupertinoSliverRefreshControl] is/// pulled a `refreshTriggerPullDistance`. Must return a [Future]. Upon132 unmodified lines/// state that gets passed into the [builder] function. Used for testing.@visibleForTestingstatic RefreshIndicatorMode state(BuildContext context) {final _CupertinoSliverRefreshControlState state = context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!;return state.refreshState;}11 unmodified linesdouble refreshTriggerPullDistance,double refreshIndicatorExtent,) {final double percentageComplete = clampDouble(pulledExtent / refreshTriggerPullDistance, 0.0, 1.0);// Place the indicator at the top of the sliver that opens up. We're using a// Stack/Positioned widget because the CupertinoActivityIndicator does some10 unmodified linestop: _kActivityIndicatorMargin,left: 0.0,right: 0.0,child: _buildIndicatorForRefreshState(refreshState, _kActivityIndicatorRadius, percentageComplete),),],),);}static Widget _buildIndicatorForRefreshState(RefreshIndicatorMode refreshState, double radius, double percentageComplete) {switch (refreshState) {case RefreshIndicatorMode.drag:// While we're dragging, we draw individual ticks of the spinner while simultaneously2 unmodified linesconst Curve opacityCurve = Interval(0.0, 0.35, curve: Curves.easeInOut);return Opacity(opacity: opacityCurve.transform(percentageComplete),child: CupertinoActivityIndicator.partiallyRevealed(radius: radius, progress: percentageComplete),);case RefreshIndicatorMode.armed:case RefreshIndicatorMode.refresh:76 unmodified lines// user supplied and we're always here in the middle of the sliver's// performLayout.SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {refreshTask = widget.onRefresh!()..whenComplete(() {if (mounted) {setState(() => refreshTask = null);// Trigger one more transition because by this time, BoxConstraint's// maxHeight might already be resting at 0 in which case no// calls to [transitionNextState] will occur anymore and the// state may be stuck in a non-inactive state.refreshState = transitionNextState();}});setState(() => hasSliverLayoutExtent = true);}, debugLabel: 'Refresh.transition');}56 unmodified lineswidget.refreshIndicatorExtent,);}return Container();},),);1 unmodified line234567891011121332 unmodified lines4647484950515253545558 unmodified lines11411511611711811912010 unmodified lines1311321331341351361371381391401411421431441451461471489 unmodified lines1581591601611621631644 unmodified lines1691701711721731741751 unmodified line17717817918018118218328 unmodified lines212213214215216217218219220221222223224225132 unmodified lines35835936036136236336436511 unmodified lines37737837938038138238338438538638710 unmodified lines3983994004014024034044054064074084094104114124134144154164174184192 unmodified lines42242342442542642742842943043176 unmodified lines50850951051151251351451551651751851952052152252352456 unmodified lines5815825835845855865871 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';////// @docImport 'app.dart';/// @docImport 'nav_bar.dart';library;import 'dart:math';import 'package:flutter/foundation.dart' show clampDouble;32 unmodified lines}@overridevoid updateRenderObject(BuildContext context,covariant _RenderCupertinoSliverRefresh renderObject,) {renderObject..refreshIndicatorLayoutExtent = refreshIndicatorLayoutExtent..hasLayoutExtent = hasLayoutExtent;58 unmodified linesassert(constraints.growthDirection == GrowthDirection.forward);// The new layout extent this sliver should now have.final double layoutExtent = (_hasLayoutExtent ? 1.0 : 0.0) * _refreshIndicatorExtent;// If the new layoutExtent instructive changed, the SliverGeometry's// layoutExtent will take that value (on the next performLayout run). Shift// the scroll offset first so it doesn't make the scroll position suddenly jump.10 unmodified lines}final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0;final double overscrolledExtent = constraints.overlap < 0.0 ? constraints.overlap.abs() : 0.0;// Layout the child giving it the space of the currently dragged overscroll// which may or may not include a sliver layout extent space that it will// keep after the user lets go during the refresh process.child!.layout(constraints.asBoxConstraints(maxExtent:layoutExtent// Plus only the overscrolled portion immediately preceding this// sliver.+overscrolledExtent,),parentUsesSize: true,);9 unmodified linesmax(child!.size.height, layoutExtent) - constraints.scrollOffset,0.0,),maxPaintExtent: max(max(child!.size.height, layoutExtent) - constraints.scrollOffset, 0.0),layoutExtent: max(layoutExtent - constraints.scrollOffset, 0.0),);} else {4 unmodified lines@overridevoid paint(PaintingContext paintContext, Offset offset) {if (constraints.overlap < 0.0 || constraints.scrollOffset + child!.size.height > 0) {paintContext.paintChild(child!, offset);}}1 unmodified line// Nothing special done here because this sliver always paints its child// exactly between paintOrigin and paintExtent.@overridevoid applyPaintTransform(RenderObject child, Matrix4 transform) {}}/// The current state of the refresh control.28 unmodified lines////// The `pulledExtent` parameter is the currently available space either from/// overscrolling or as held by the sliver during refresh.typedef RefreshControlIndicatorBuilder =Widget Function(BuildContext context,RefreshIndicatorMode refreshState,double pulledExtent,double refreshTriggerPullDistance,double refreshIndicatorExtent,);/// A callback function that's invoked when the [CupertinoSliverRefreshControl] is/// pulled a `refreshTriggerPullDistance`. Must return a [Future]. Upon132 unmodified lines/// state that gets passed into the [builder] function. Used for testing.@visibleForTestingstatic RefreshIndicatorMode state(BuildContext context) {final _CupertinoSliverRefreshControlState state =context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!;return state.refreshState;}11 unmodified linesdouble refreshTriggerPullDistance,double refreshIndicatorExtent,) {final double percentageComplete = clampDouble(pulledExtent / refreshTriggerPullDistance,0.0,1.0,);// Place the indicator at the top of the sliver that opens up. We're using a// Stack/Positioned widget because the CupertinoActivityIndicator does some10 unmodified linestop: _kActivityIndicatorMargin,left: 0.0,right: 0.0,child: _buildIndicatorForRefreshState(refreshState,_kActivityIndicatorRadius,percentageComplete,),),],),);}static Widget _buildIndicatorForRefreshState(RefreshIndicatorMode refreshState,double radius,double percentageComplete,) {switch (refreshState) {case RefreshIndicatorMode.drag:// While we're dragging, we draw individual ticks of the spinner while simultaneously2 unmodified linesconst Curve opacityCurve = Interval(0.0, 0.35, curve: Curves.easeInOut);return Opacity(opacity: opacityCurve.transform(percentageComplete),child: CupertinoActivityIndicator.partiallyRevealed(radius: radius,progress: percentageComplete,),);case RefreshIndicatorMode.armed:case RefreshIndicatorMode.refresh:76 unmodified lines// user supplied and we're always here in the middle of the sliver's// performLayout.SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {refreshTask =widget.onRefresh!()..whenComplete(() {if (mounted) {setState(() => refreshTask = null);// Trigger one more transition because by this time, BoxConstraint's// maxHeight might already be resting at 0 in which case no// calls to [transitionNextState] will occur anymore and the// state may be stuck in a non-inactive state.refreshState = transitionNextState();}});setState(() => hasSliverLayoutExtent = true);}, debugLabel: 'Refresh.transition');}56 unmodified lineswidget.refreshIndicatorExtent,);}return const LimitedBox(maxWidth: 0.0, maxHeight: 0.0, child: SizedBox.expand());},),);
1 unmodified line234567891011124 unmodified lines1718192021222324252627282928 unmodified lines5859606162636464 unmodified lines1291301311321331341351361372 unmodified lines1401411421431441451461471484 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125224 unmodified lines2772782792802812822837 unmodified lines2912922932942952962972 unmodified lines30030130230330430530633 unmodified lines3403413423433443452 unmodified lines34834935035135235315 unmodified lines36937037137237337437537637737837938038136 unmodified lines41841942042142242325 unmodified lines4494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035046 unmodified lines5115125135145155165175185195203 unmodified lines5245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675682 unmodified lines57157257357457557657757857958035 unmodified lines61661761861962062162262362462562621 unmodified lines64864965065165265365465565665765865966012 unmodified lines6736746756766776786796806816826836841 unmodified line68668768868969069169269369469569669769869970070170270370470570670770817 unmodified lines72672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078123 unmodified lines80580680780880981081181281381435 unmodified lines85085185285385485585685785885986086186286386486586686786886987013 unmodified lines8848858868878888898902 unmodified lines8938948958968978988999008 unmodified lines90991091191291391491591691791834 unmodified lines95395495595695795895996096196296396496596696796896997097197297397497597697797897998098198239 unmodified lines10221023102410251026102727 unmodified lines105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110629 unmodified lines11361137113811391140114135 unmodified lines1177117811791180118111824 unmodified lines118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122016 unmodified lines12371238123912401241124229 unmodified lines12721273127412751276127712782 unmodified lines1281128212831284128512861287128812891290129112921293129412951296129743 unmodified lines134113421343134413451346134713481349135013511352135313541 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math';import 'dart:ui' show ImageFilter, lerpDouble;import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter/widgets.dart';4 unmodified linesconst double _kBackGestureWidth = 20.0;const double _kMinFlingVelocity = 1.0; // Screen widths per second.// An eyeballed value for the maximum time it takes for a page to animate forward// if the user releases a page mid swipe.const int _kMaxDroppedSwipePageForwardAnimationTime = 800; // Milliseconds.// The maximum time for a page to get reset to it's original position if the// user releases a page mid swipe.const int _kMaxPageBackAnimationTime = 300; // Milliseconds./// Barrier color used for a barrier visible during transitions for Cupertino/// page routes.28 unmodified lines// Offset from fully on screen to 1/3 offscreen to the left.final Animatable<Offset> _kMiddleLeftTween = Tween<Offset>(begin: Offset.zero,end: const Offset(-1.0/3.0, 0.0),);// Offset from offscreen below to fully on screen.64 unmodified lines@overridevoid didChangePrevious(Route<dynamic>? previousRoute) {final String? previousTitleString = previousRoute is CupertinoRouteTransitionMixin? previousRoute.title: null;if (_previousTitle == null) {_previousTitle = ValueNotifier<String?>(previousTitleString);} else {2 unmodified linessuper.didChangePrevious(previousRoute);}@override// A relatively rigorous eyeball estimation.Duration get transitionDuration => const Duration(milliseconds: 500);@overrideColor? get barrierColor => fullscreenDialog ? null : _kCupertinoPageTransitionBarrierColor;4 unmodified lines@overridebool canTransitionTo(TransitionRoute<dynamic> nextRoute) {// Don't perform outgoing animation if the next route is a fullscreen dialog.return nextRoute is CupertinoRouteTransitionMixin && !nextRoute.fullscreenDialog;}/// True if an iOS-style back swipe pop gesture is currently underway for [route].////// This just check the route's [NavigatorState.userGestureInProgress].////// See also:////// * [popGestureEnabled], which returns true if a user-triggered pop gesture/// would be allowed.static bool isPopGestureInProgress(PageRoute<dynamic> route) {return route.navigator!.userGestureInProgress;}/// True if an iOS-style back swipe pop gesture is currently underway for this route.////// See also:////// * [isPopGestureInProgress], which returns true if a Cupertino pop gesture/// is currently underway for specific route./// * [popGestureEnabled], which returns true if a user-triggered pop gesture/// would be allowed.bool get popGestureInProgress => isPopGestureInProgress(this);/// Whether a pop gesture can be started by the user.////// Returns true if the user can edge-swipe to a previous route.////// Returns false once [isPopGestureInProgress] is true, but/// [isPopGestureInProgress] can only become true if [popGestureEnabled] was/// true first.////// This should only be used between frames, not during build.bool get popGestureEnabled => _isPopGestureEnabled(this);static bool _isPopGestureEnabled<T>(PageRoute<T> route) {// If there's nothing to go back to, then obviously we don't support// the back gesture.if (route.isFirst) {return false;}// If the route wouldn't actually pop if we popped it, then the gesture// would be really confusing (or would skip internal routes), so disallow it.if (route.willHandlePopInternally) {return false;}// If attempts to dismiss this route might be vetoed such as in a page// with forms, then do not allow the user to dismiss the route with a swipe.if (route.hasScopedWillPopCallback|| route.popDisposition == RoutePopDisposition.doNotPop) {return false;}// Fullscreen dialogs aren't dismissible by back swipe.if (route.fullscreenDialog) {return false;}// If we're in an animation already, we cannot be manually swiped.if (route.animation!.status != AnimationStatus.completed) {return false;}// If we're being popped into, we also cannot be swiped until the pop above// it completes. This translates to our secondary animation being// dismissed.if (route.secondaryAnimation!.status != AnimationStatus.dismissed) {return false;}// If we're in a gesture already, we cannot start another.if (isPopGestureInProgress(route)) {return false;}// Looks like a back gesture would be welcome!return true;}@overrideWidget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {final Widget child = buildContent(context);return Semantics(scopesRoute: true,explicitChildNodes: true,child: child,);}// Called by _CupertinoBackGestureDetector when a pop ("back") drag start// gesture is detected. The returned controller handles all of the subsequent// drag events.static _CupertinoBackGestureController<T> _startPopGesture<T>(PageRoute<T> route) {assert(_isPopGestureEnabled(route));return _CupertinoBackGestureController<T>(navigator: route.navigator!,controller: route.controller!, // protected access);}24 unmodified lines//// In the middle of a back gesture drag, let the transition be linear to// match finger motions.final bool linearTransition = isPopGestureInProgress(route);if (route.fullscreenDialog) {return CupertinoFullscreenDialogTransition(primaryRouteAnimation: animation,7 unmodified linessecondaryRouteAnimation: secondaryAnimation,linearTransition: linearTransition,child: _CupertinoBackGestureDetector<T>(enabledCallback: () => _isPopGestureEnabled<T>(route),onStartPopGesture: () => _startPopGesture<T>(route),child: child,),2 unmodified lines}@overrideWidget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {return buildPageTransitions<T>(this, context, animation, secondaryAnimation, child);}}33 unmodified linesrequired this.builder,this.title,super.settings,this.maintainState = true,super.fullscreenDialog,super.allowSnapshotting = true,2 unmodified linesassert(opaque);}/// Builds the primary contents of the route.final WidgetBuilder builder;15 unmodified lines// This route uses the builder from the page to build its content. This ensures// the content is up to date after page updates.class _PageBasedCupertinoPageRoute<T> extends PageRoute<T> with CupertinoRouteTransitionMixin<T> {_PageBasedCupertinoPageRoute({required CupertinoPage<T> page,super.allowSnapshotting = true,}) : super(settings: page) {assert(opaque);}CupertinoPage<T> get _page => settings as CupertinoPage<T>;@override36 unmodified linesthis.title,this.fullscreenDialog = false,this.allowSnapshotting = true,super.key,super.name,super.arguments,25 unmodified lines////// The page slides in from the right and exits in reverse. It also shifts to the left in/// a parallax motion when another page enters to cover it.class CupertinoPageTransition extends StatelessWidget {/// Creates an iOS-style page transition.////// * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when this screen is being pushed./// * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when another screen is being pushed on top of this one./// * `linearTransition` is whether to perform the transitions linearly./// Used to precisely track back gesture drags.CupertinoPageTransition({super.key,required Animation<double> primaryRouteAnimation,required Animation<double> secondaryRouteAnimation,required this.child,required bool linearTransition,}) : _primaryPositionAnimation =(linearTransition? primaryRouteAnimation: CurvedAnimation(parent: primaryRouteAnimation,curve: Curves.fastEaseInToSlowEaseOut,reverseCurve: Curves.fastEaseInToSlowEaseOut.flipped,)).drive(_kRightMiddleTween),_secondaryPositionAnimation =(linearTransition? secondaryRouteAnimation: CurvedAnimation(parent: secondaryRouteAnimation,curve: Curves.linearToEaseOut,reverseCurve: Curves.easeInToLinear,)).drive(_kMiddleLeftTween),_primaryShadowAnimation =(linearTransition? primaryRouteAnimation: CurvedAnimation(parent: primaryRouteAnimation,curve: Curves.linearToEaseOut,)).drive(_CupertinoEdgeShadowDecoration.kTween);// When this page is coming in to cover another page.final Animation<Offset> _primaryPositionAnimation;// When this page is becoming covered by another page.final Animation<Offset> _secondaryPositionAnimation;final Animation<Decoration> _primaryShadowAnimation;/// The widget below this widget in the tree.final Widget child;@overrideWidget build(BuildContext context) {6 unmodified lineschild: SlideTransition(position: _primaryPositionAnimation,textDirection: textDirection,child: DecoratedBoxTransition(decoration: _primaryShadowAnimation,child: child,),),);}3 unmodified lines////// For example, used when creating a new calendar event by bringing in the next/// screen from the bottom.class CupertinoFullscreenDialogTransition extends StatelessWidget {/// Creates an iOS-style transition used for summoning fullscreen dialogs.////// * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when this screen is being pushed./// * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when another screen is being pushed on top of this one./// * `linearTransition` is whether to perform the secondary transition linearly./// Used to precisely track back gesture drags.CupertinoFullscreenDialogTransition({super.key,required Animation<double> primaryRouteAnimation,required Animation<double> secondaryRouteAnimation,required this.child,required bool linearTransition,}) : _positionAnimation = CurvedAnimation(parent: primaryRouteAnimation,curve: Curves.linearToEaseOut,// The curve must be flipped so that the reverse animation doesn't play// an ease-in curve, which iOS does not use.reverseCurve: Curves.linearToEaseOut.flipped,).drive(_kBottomUpTween),_secondaryPositionAnimation =(linearTransition? secondaryRouteAnimation: CurvedAnimation(parent: secondaryRouteAnimation,curve: Curves.linearToEaseOut,reverseCurve: Curves.easeInToLinear,)).drive(_kMiddleLeftTween);final Animation<Offset> _positionAnimation;// When this page is becoming covered by another page.final Animation<Offset> _secondaryPositionAnimation;/// The widget below this widget in the tree.final Widget child;@overrideWidget build(BuildContext context) {assert(debugCheckHasDirectionality(context));2 unmodified linesposition: _secondaryPositionAnimation,textDirection: textDirection,transformHitTests: false,child: SlideTransition(position: _positionAnimation,child: child,),);}}35 unmodified lines@overridevoid initState() {super.initState();_recognizer = HorizontalDragGestureRecognizer(debugOwner: this)..onStart = _handleDragStart..onUpdate = _handleDragUpdate..onEnd = _handleDragEnd..onCancel = _handleDragCancel;}@override21 unmodified linesvoid _handleDragUpdate(DragUpdateDetails details) {assert(mounted);assert(_backGestureController != null);_backGestureController!.dragUpdate(_convertToLogical(details.primaryDelta! / context.size!.width));}void _handleDragEnd(DragEndDetails details) {assert(mounted);assert(_backGestureController != null);_backGestureController!.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size!.width));_backGestureController = null;}12 unmodified lines}double _convertToLogical(double value) {switch (Directionality.of(context)) {case TextDirection.rtl:return -value;case TextDirection.ltr:return value;}}@override1 unmodified lineassert(debugCheckHasDirectionality(context));// For devices with notches, the drag area needs to be larger on the side// that has the notch.double dragAreaWidth = Directionality.of(context) == TextDirection.ltr ?MediaQuery.paddingOf(context).left :MediaQuery.paddingOf(context).right;dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth);return Stack(fit: StackFit.passthrough,children: <Widget>[widget.child,PositionedDirectional(start: 0.0,width: dragAreaWidth,top: 0.0,bottom: 0.0,child: Listener(onPointerDown: _handlePointerDown,behavior: HitTestBehavior.translucent,),),],);17 unmodified lines_CupertinoBackGestureController({required this.navigator,required this.controller,}) {navigator.didStartUserGesture();}final AnimationController controller;final NavigatorState navigator;/// The drag gesture has changed by [fractionalDelta]. The total range of the/// drag should be 0.0 to 1.0.void dragUpdate(double delta) {controller.value -= delta;}/// The drag gesture has ended with a horizontal motion of/// [fractionalVelocity] as a fraction of screen width per second.void dragEnd(double velocity) {// Fling in the appropriate direction.//// This curve has been determined through rigorously eyeballing native iOS// animations.const Curve animationCurve = Curves.fastLinearToSlowEaseIn;final bool animateForward;// If the user releases the page before mid screen with sufficient velocity,// or after mid screen, we should animate the page out. Otherwise, the page// should be animated back in.if (velocity.abs() >= _kMinFlingVelocity) {animateForward = velocity <= 0;} else {animateForward = controller.value > 0.5;}if (animateForward) {// The closer the panel is to dismissing, the shorter the animation is.// We want to cap the animation time, but we want to use a linear curve// to determine it.final int droppedPageForwardAnimationTime = min(lerpDouble(_kMaxDroppedSwipePageForwardAnimationTime, 0, controller.value)!.floor(),_kMaxPageBackAnimationTime,);controller.animateTo(1.0, duration: Duration(milliseconds: droppedPageForwardAnimationTime), curve: animationCurve);} else {// This route is destined to pop at this point. Reuse navigator's pop.navigator.pop();// The popping may have finished inline if already at the target destination.if (controller.isAnimating) {// Otherwise, use a custom popping animation duration and curve.final int droppedPageBackAnimationTime = lerpDouble(0, _kMaxDroppedSwipePageForwardAnimationTime, controller.value)!.floor();controller.animateBack(0.0, duration: Duration(milliseconds: droppedPageBackAnimationTime), curve: animationCurve);}}23 unmodified linesbegin: const _CupertinoEdgeShadowDecoration._(), // No decoration initially.end: const _CupertinoEdgeShadowDecoration._(// Eyeballed gradient used to mimic a drop shadow on the start side only.<Color>[Color(0x04000000),Color(0x00000000),],),);35 unmodified linesreturn a;}if (a == null) {return b!._colors == null ? b : _CupertinoEdgeShadowDecoration._(b._colors!.map<Color>((Color color) => Color.lerp(null, color, t)!).toList());}if (b == null) {return a._colors == null ? a : _CupertinoEdgeShadowDecoration._(a._colors.map<Color>((Color color) => Color.lerp(null, color, 1.0 - t)!).toList());}assert(b._colors != null || a._colors != null);// If it ever becomes necessary, we could allow decorations with different// length' here, similarly to how it is handled in [LinearGradient.lerp].assert(b._colors == null || a._colors == null || a._colors.length == b._colors.length);return _CupertinoEdgeShadowDecoration._(<Color>[for (int i = 0; i < b._colors!.length; i += 1)Color.lerp(a._colors?[i], b._colors[i], t)!,],);}@override13 unmodified lines}@override_CupertinoEdgeShadowPainter createBoxPainter([ VoidCallback? onChanged ]) {return _CupertinoEdgeShadowPainter(this, onChanged);}2 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is _CupertinoEdgeShadowDecoration&& other._colors == _colors;}@override8 unmodified lines/// A [BoxPainter] used to draw the page transition shadow using gradients.class _CupertinoEdgeShadowPainter extends BoxPainter {_CupertinoEdgeShadowPainter(this._decoration,super.onChanged,) : assert(_decoration._colors == null || _decoration._colors.length > 1);final _CupertinoEdgeShadowDecoration _decoration;34 unmodified linesfinal TextDirection? textDirection = configuration.textDirection;assert(textDirection != null);final double start;final double shadowDirection; // -1 for ltr, 1 for rtl.switch (textDirection!) {case TextDirection.rtl:start = offset.dx + configuration.size!.width;shadowDirection = 1;case TextDirection.ltr:start = offset.dx;shadowDirection = -1;}int bandColorIndex = 0;for (int dx = 0; dx < shadowWidth; dx += 1) {if (dx ~/ bandWidth != bandColorIndex) {bandColorIndex += 1;}final Paint paint = Paint()..color = Color.lerp(colors[bandColorIndex], colors[bandColorIndex + 1], (dx % bandWidth) / bandWidth)!;final double x = start + shadowDirection * dx;canvas.drawRect(Rect.fromLTWH(x - 1.0, offset.dy, 1.0, shadowHeight), paint);}}}/// A route that shows a modal iOS-style popup that slides up from the/// bottom of the screen.///39 unmodified linesbool semanticsDismissible = false,super.filter,super.settings,this.anchorPoint,}) : _barrierDismissible = barrierDismissible,_semanticsDismissible = semanticsDismissible;27 unmodified lines@overrideDuration get transitionDuration => _kModalPopupTransitionDuration;Animation<double>? _animation;late Tween<Offset> _offsetTween;/// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}final Offset? anchorPoint;@overrideAnimation<double> createAnimation() {assert(_animation == null);_animation = CurvedAnimation(parent: super.createAnimation(),// These curves were initially measured from native iOS horizontal page// route animations and seemed to be a good match here as well.curve: Curves.linearToEaseOut,reverseCurve: Curves.linearToEaseOut.flipped,);_offsetTween = Tween<Offset>(begin: const Offset(0.0, 1.0),end: Offset.zero,);return _animation!;}@overrideWidget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {return CupertinoUserInterfaceLevel(data: CupertinoUserInterfaceLevelData.elevated,child: DisplayFeatureSubScreen(anchorPoint: anchorPoint,child: Builder(builder: builder),),);}@overrideWidget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {return Align(alignment: Alignment.bottomCenter,child: FractionalTranslation(translation: _offsetTween.evaluate(_animation!),child: child,),);}}/// Shows a modal iOS-style popup that slides up from the bottom of the screen.29 unmodified lines/// [StatefulBuilder] or a custom [StatefulWidget] if the widget needs to/// update dynamically.////// {@macro flutter.widgets.RawDialogRoute}////// Returns a `Future` that resolves to the value that was passed to35 unmodified linesbool semanticsDismissible = false,RouteSettings? routeSettings,Offset? anchorPoint,}) {return Navigator.of(context, rootNavigator: useRootNavigator).push(CupertinoModalPopupRoute<T>(4 unmodified linessemanticsDismissible: semanticsDismissible,settings: routeSettings,anchorPoint: anchorPoint,),);}// The curve and initial scale values were mostly eyeballed from iOS, however// they reuse the same animation curve that was modeled after native page// transitions.final Animatable<double> _dialogScaleTween = Tween<double>(begin: 1.3, end: 1.0).chain(CurveTween(curve: Curves.linearToEaseOut));Widget _buildCupertinoDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {final CurvedAnimation fadeAnimation = CurvedAnimation(parent: animation,curve: Curves.easeInOut,);if (animation.status == AnimationStatus.reverse) {return FadeTransition(opacity: fadeAnimation,child: child,);}return FadeTransition(opacity: fadeAnimation,child: ScaleTransition(scale: animation.drive(_dialogScaleTween),child: child,),);}/// Displays an iOS-style dialog above the current contents of the app, with16 unmodified lines/// By default, `useRootNavigator` is `true` and the dialog route created by/// this method is pushed to the root navigator.////// {@macro flutter.widgets.RawDialogRoute}////// If the application has multiple [Navigator] objects, it may be necessary to29 unmodified lines/// * [showGeneralDialog], which allows for customization of the dialog popup./// * [DisplayFeatureSubScreen], which documents the specifics of how/// [DisplayFeature]s can split the screen into sub-screens./// * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>Future<T?> showCupertinoDialog<T>({required BuildContext context,required WidgetBuilder builder,2 unmodified linesbool barrierDismissible = false,RouteSettings? routeSettings,Offset? anchorPoint,}) {return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(CupertinoDialogRoute<T>(builder: builder,context: context,barrierDismissible: barrierDismissible,barrierLabel: barrierLabel,barrierColor: CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),settings: routeSettings,anchorPoint: anchorPoint,));}/// A dialog route that shows an iOS-style dialog.43 unmodified linesString? barrierLabel,// This transition duration was eyeballed comparing with iOSsuper.transitionDuration = const Duration(milliseconds: 250),super.transitionBuilder = _buildCupertinoDialogTransitions,super.settings,super.anchorPoint,}) : super(pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {return builder(context);},barrierLabel: barrierLabel ?? CupertinoLocalizations.of(context).modalBarrierDismissLabel,barrierColor: barrierColor ?? CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),);}1 unmodified line2345678910111213141516171819202122232425264 unmodified lines313233343536373828 unmodified lines6768697071727364 unmodified lines1381391401411421431441452 unmodified lines1481491501511521531541551561571581591604 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021124 unmodified lines2362372382392402412427 unmodified lines2502512522532542552562 unmodified lines25926026126226326426526626726826927033 unmodified lines3043053063073083093102 unmodified lines31331431531631731831932032132215 unmodified lines33833934034134234334434534634734834935035135236 unmodified lines38939039139239339439539625 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585596 unmodified lines5665675685695705715723 unmodified lines5765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736742 unmodified lines67767867968068168268335 unmodified lines71972072172272372472572672772872973021 unmodified lines75275375475575675775875976076176276376476576676776812 unmodified lines7817827837847857867877887897901 unmodified line79279379479579679779879980080180280380480580680780880981081117 unmodified lines82983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789823 unmodified lines92292392492592692792835 unmodified lines96496596696796896997097197297397497597697797897998098198298398498598698798898913 unmodified lines10031004100510061007100810092 unmodified lines10121013101410151016101710188 unmodified lines1027102810291030103110321033103434 unmodified lines10691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112239 unmodified lines116211631164116511661167116827 unmodified lines119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124729 unmodified lines127712781279128012811282128312841285128635 unmodified lines13221323132413251326132713284 unmodified lines13331334133513361337133813391340134113421343134413451346134713481349135016 unmodified lines13671368136913701371137213731374137529 unmodified lines14051406140714081409141014112 unmodified lines1414141514161417141814191420142114221423142414251426142714281429143014311432143343 unmodified lines147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'dart:ui';////// @docImport 'package:flutter/material.dart';/// @docImport 'package:flutter/services.dart';////// @docImport 'app.dart';/// @docImport 'button.dart';/// @docImport 'dialog.dart';/// @docImport 'nav_bar.dart';/// @docImport 'page_scaffold.dart';/// @docImport 'tab_scaffold.dart';library;import 'dart:math';import 'dart:ui' show ImageFilter;import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/physics.dart';import 'package:flutter/rendering.dart';import 'package:flutter/widgets.dart';4 unmodified linesconst double _kBackGestureWidth = 20.0;const double _kMinFlingVelocity = 1.0; // Screen widths per second.// The duration for a page to animate when the user releases it mid-swipe.const Duration _kDroppedSwipePageAnimationDuration = Duration(milliseconds: 350);/// Barrier color used for a barrier visible during transitions for Cupertino/// page routes.28 unmodified lines// Offset from fully on screen to 1/3 offscreen to the left.final Animatable<Offset> _kMiddleLeftTween = Tween<Offset>(begin: Offset.zero,end: const Offset(-1.0 / 3.0, 0.0),);// Offset from offscreen below to fully on screen.64 unmodified lines@overridevoid didChangePrevious(Route<dynamic>? previousRoute) {final String? previousTitleString =previousRoute is CupertinoRouteTransitionMixin ? previousRoute.title : null;if (_previousTitle == null) {_previousTitle = ValueNotifier<String?>(previousTitleString);} else {2 unmodified linessuper.didChangePrevious(previousRoute);}/// The duration of the page transition.////// A relatively rigorous eyeball estimation.static const Duration kTransitionDuration = Duration(milliseconds: 500);@overrideDuration get transitionDuration => kTransitionDuration;@overrideColor? get barrierColor => fullscreenDialog ? null : _kCupertinoPageTransitionBarrierColor;4 unmodified lines@overridebool canTransitionTo(TransitionRoute<dynamic> nextRoute) {// Don't perform outgoing animation if the next route is a fullscreen dialog.final bool nextRouteIsNotFullscreen =(nextRoute is! PageRoute<T>) || !nextRoute.fullscreenDialog;// If the next route has a delegated transition, then this route is able to// use that delegated transition to smoothly sync with the next route's// transition.final bool nextRouteHasDelegatedTransition =nextRoute is ModalRoute<T> && nextRoute.delegatedTransition != null;// Otherwise if the next route has the same route transition mixin as this// one, then this route will already be synced with its transition.return nextRouteIsNotFullscreen &&((nextRoute is CupertinoRouteTransitionMixin) || nextRouteHasDelegatedTransition);}@overridebool canTransitionFrom(TransitionRoute<dynamic> previousRoute) {// Supress previous route from transitioning if this is a fullscreenDialog route.return previousRoute is PageRoute && !fullscreenDialog;}@overrideWidget buildPage(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,) {final Widget child = buildContent(context);return Semantics(scopesRoute: true, explicitChildNodes: true, child: child);}// Called by _CupertinoBackGestureDetector when a pop ("back") drag start// gesture is detected. The returned controller handles all of the subsequent// drag events.static _CupertinoBackGestureController<T> _startPopGesture<T>(PageRoute<T> route) {assert(route.popGestureEnabled);return _CupertinoBackGestureController<T>(navigator: route.navigator!,getIsCurrent: () => route.isCurrent,getIsActive: () => route.isActive,controller: route.controller!, // protected access);}24 unmodified lines//// In the middle of a back gesture drag, let the transition be linear to// match finger motions.final bool linearTransition = route.popGestureInProgress;if (route.fullscreenDialog) {return CupertinoFullscreenDialogTransition(primaryRouteAnimation: animation,7 unmodified linessecondaryRouteAnimation: secondaryAnimation,linearTransition: linearTransition,child: _CupertinoBackGestureDetector<T>(enabledCallback: () => route.popGestureEnabled,onStartPopGesture: () => _startPopGesture<T>(route),child: child,),2 unmodified lines}@overrideWidget buildTransitions(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,Widget child,) {return buildPageTransitions<T>(this, context, animation, secondaryAnimation, child);}}33 unmodified linesrequired this.builder,this.title,super.settings,super.requestFocus,this.maintainState = true,super.fullscreenDialog,super.allowSnapshotting = true,2 unmodified linesassert(opaque);}@overrideDelegatedTransitionBuilder? get delegatedTransition =>CupertinoPageTransition.delegatedTransition;/// Builds the primary contents of the route.final WidgetBuilder builder;15 unmodified lines// This route uses the builder from the page to build its content. This ensures// the content is up to date after page updates.class _PageBasedCupertinoPageRoute<T> extends PageRoute<T> with CupertinoRouteTransitionMixin<T> {_PageBasedCupertinoPageRoute({required CupertinoPage<T> page, super.allowSnapshotting = true}): super(settings: page) {assert(opaque);}@overrideDelegatedTransitionBuilder? get delegatedTransition =>this.fullscreenDialog ? null : CupertinoPageTransition.delegatedTransition;CupertinoPage<T> get _page => settings as CupertinoPage<T>;@override36 unmodified linesthis.title,this.fullscreenDialog = false,this.allowSnapshotting = true,super.canPop,super.onPopInvoked,super.key,super.name,super.arguments,25 unmodified lines////// The page slides in from the right and exits in reverse. It also shifts to the left in/// a parallax motion when another page enters to cover it.class CupertinoPageTransition extends StatefulWidget {/// Creates an iOS-style page transition.///const CupertinoPageTransition({super.key,required this.primaryRouteAnimation,required this.secondaryRouteAnimation,required this.child,required this.linearTransition,});/// The widget below this widget in the tree.final Widget child;/// * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when this screen is being pushed.final Animation<double> primaryRouteAnimation;/// * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when another screen is being pushed on top of this one.final Animation<double> secondaryRouteAnimation;/// * `linearTransition` is whether to perform the transitions linearly./// Used to precisely track back gesture drags.final bool linearTransition;/// The Cupertino styled [DelegatedTransitionBuilder] provided to the previous/// route.////// {@macro flutter.widgets.delegatedTransition}static Widget? delegatedTransition(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,bool allowSnapshotting,Widget? child,) {final CurvedAnimation animation = CurvedAnimation(parent: secondaryAnimation,curve: Curves.linearToEaseOut,reverseCurve: Curves.easeInToLinear,);final Animation<Offset> delegatedPositionAnimation = animation.drive(_kMiddleLeftTween);animation.dispose();assert(debugCheckHasDirectionality(context));final TextDirection textDirection = Directionality.of(context);return SlideTransition(position: delegatedPositionAnimation,textDirection: textDirection,transformHitTests: false,child: child,);}@overrideState<CupertinoPageTransition> createState() => _CupertinoPageTransitionState();}class _CupertinoPageTransitionState extends State<CupertinoPageTransition> {// When this page is coming in to cover another page.late Animation<Offset> _primaryPositionAnimation;// When this page is becoming covered by another page.late Animation<Offset> _secondaryPositionAnimation;// Shadow of page which is coming in to cover another page.late Animation<Decoration> _primaryShadowAnimation;// Curve of primary page which is coming in to cover another page.CurvedAnimation? _primaryPositionCurve;// Curve of secondary page which is becoming covered by another page.CurvedAnimation? _secondaryPositionCurve;// Curve of primary page's shadow.CurvedAnimation? _primaryShadowCurve;@overridevoid initState() {super.initState();_setupAnimation();}@overridevoid didUpdateWidget(covariant CupertinoPageTransition oldWidget) {super.didUpdateWidget(oldWidget);if (oldWidget.primaryRouteAnimation != widget.primaryRouteAnimation ||oldWidget.secondaryRouteAnimation != widget.secondaryRouteAnimation ||oldWidget.linearTransition != widget.linearTransition) {_disposeCurve();_setupAnimation();}}@overridevoid dispose() {_disposeCurve();super.dispose();}void _disposeCurve() {_primaryPositionCurve?.dispose();_secondaryPositionCurve?.dispose();_primaryShadowCurve?.dispose();_primaryPositionCurve = null;_secondaryPositionCurve = null;_primaryShadowCurve = null;}void _setupAnimation() {if (!widget.linearTransition) {_primaryPositionCurve = CurvedAnimation(parent: widget.primaryRouteAnimation,curve: Curves.fastEaseInToSlowEaseOut,reverseCurve: Curves.fastEaseInToSlowEaseOut.flipped,);_secondaryPositionCurve = CurvedAnimation(parent: widget.secondaryRouteAnimation,curve: Curves.linearToEaseOut,reverseCurve: Curves.easeInToLinear,);_primaryShadowCurve = CurvedAnimation(parent: widget.primaryRouteAnimation,curve: Curves.linearToEaseOut,);}_primaryPositionAnimation = (_primaryPositionCurve ?? widget.primaryRouteAnimation).drive(_kRightMiddleTween,);_secondaryPositionAnimation = (_secondaryPositionCurve ?? widget.secondaryRouteAnimation).drive(_kMiddleLeftTween,);_primaryShadowAnimation = (_primaryShadowCurve ?? widget.primaryRouteAnimation).drive(_CupertinoEdgeShadowDecoration.kTween,);}@overrideWidget build(BuildContext context) {6 unmodified lineschild: SlideTransition(position: _primaryPositionAnimation,textDirection: textDirection,child: DecoratedBoxTransition(decoration: _primaryShadowAnimation, child: widget.child),),);}3 unmodified lines////// For example, used when creating a new calendar event by bringing in the next/// screen from the bottom.class CupertinoFullscreenDialogTransition extends StatefulWidget {/// Creates an iOS-style transition used for summoning fullscreen dialogs.///const CupertinoFullscreenDialogTransition({super.key,required this.primaryRouteAnimation,required this.secondaryRouteAnimation,required this.child,required this.linearTransition,});/// * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when this screen is being pushed.final Animation<double> primaryRouteAnimation;/// * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0/// when another screen is being pushed on top of this one.final Animation<double> secondaryRouteAnimation;/// * `linearTransition` is whether to perform the transitions linearly./// Used to precisely track back gesture drags.final bool linearTransition;/// The widget below this widget in the tree.final Widget child;@overrideState<CupertinoFullscreenDialogTransition> createState() =>_CupertinoFullscreenDialogTransitionState();}class _CupertinoFullscreenDialogTransitionState extends State<CupertinoFullscreenDialogTransition> {/// When this page is coming in to cover another page.late Animation<Offset> _primaryPositionAnimation;/// When this page is becoming covered by another page.late Animation<Offset> _secondaryPositionAnimation;/// Curve of primary page which is coming in to cover another page.CurvedAnimation? _primaryPositionCurve;/// Curve of secondary page which is becoming covered by another page.CurvedAnimation? _secondaryPositionCurve;@overridevoid initState() {super.initState();_setupAnimation();}@overridevoid didUpdateWidget(covariant CupertinoFullscreenDialogTransition oldWidget) {super.didUpdateWidget(oldWidget);if (oldWidget.primaryRouteAnimation != widget.primaryRouteAnimation ||oldWidget.secondaryRouteAnimation != widget.secondaryRouteAnimation ||oldWidget.linearTransition != widget.linearTransition) {_disposeCurve();_setupAnimation();}}@overridevoid dispose() {_disposeCurve();super.dispose();}void _disposeCurve() {_primaryPositionCurve?.dispose();_secondaryPositionCurve?.dispose();_primaryPositionCurve = null;_secondaryPositionCurve = null;}void _setupAnimation() {_primaryPositionAnimation = (_primaryPositionCurve = CurvedAnimation(parent: widget.primaryRouteAnimation,curve: Curves.linearToEaseOut,// The curve must be flipped so that the reverse animation doesn't play// an ease-in curve, which iOS does not use.reverseCurve: Curves.linearToEaseOut.flipped,)).drive(_kBottomUpTween);_secondaryPositionAnimation = (widget.linearTransition? widget.secondaryRouteAnimation: _secondaryPositionCurve = CurvedAnimation(parent: widget.secondaryRouteAnimation,curve: Curves.linearToEaseOut,reverseCurve: Curves.easeInToLinear,)).drive(_kMiddleLeftTween);}@overrideWidget build(BuildContext context) {assert(debugCheckHasDirectionality(context));2 unmodified linesposition: _secondaryPositionAnimation,textDirection: textDirection,transformHitTests: false,child: SlideTransition(position: _primaryPositionAnimation, child: widget.child),);}}35 unmodified lines@overridevoid initState() {super.initState();_recognizer =HorizontalDragGestureRecognizer(debugOwner: this)..onStart = _handleDragStart..onUpdate = _handleDragUpdate..onEnd = _handleDragEnd..onCancel = _handleDragCancel;}@override21 unmodified linesvoid _handleDragUpdate(DragUpdateDetails details) {assert(mounted);assert(_backGestureController != null);_backGestureController!.dragUpdate(_convertToLogical(details.primaryDelta! / context.size!.width),);}void _handleDragEnd(DragEndDetails details) {assert(mounted);assert(_backGestureController != null);_backGestureController!.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size!.width),);_backGestureController = null;}12 unmodified lines}double _convertToLogical(double value) {return switch (Directionality.of(context)) {TextDirection.rtl => -value,TextDirection.ltr => value,};}@override1 unmodified lineassert(debugCheckHasDirectionality(context));// For devices with notches, the drag area needs to be larger on the side// that has the notch.final double dragAreaWidth = switch (Directionality.of(context)) {TextDirection.rtl => MediaQuery.paddingOf(context).right,TextDirection.ltr => MediaQuery.paddingOf(context).left,};return Stack(fit: StackFit.passthrough,children: <Widget>[widget.child,PositionedDirectional(start: 0.0,width: max(dragAreaWidth, _kBackGestureWidth),top: 0.0,bottom: 0.0,child: Listener(onPointerDown: _handlePointerDown, behavior: HitTestBehavior.translucent),),],);17 unmodified lines_CupertinoBackGestureController({required this.navigator,required this.controller,required this.getIsActive,required this.getIsCurrent,}) {navigator.didStartUserGesture();}final AnimationController controller;final NavigatorState navigator;final ValueGetter<bool> getIsActive;final ValueGetter<bool> getIsCurrent;/// The drag gesture has changed by [delta]. The total range of the drag/// should be 0.0 to 1.0.void dragUpdate(double delta) {controller.value -= delta;}/// The drag gesture has ended with a horizontal motion of [velocity] as a/// fraction of screen width per second.void dragEnd(double velocity) {// Fling in the appropriate direction.//// This curve has been determined through rigorously eyeballing native iOS// animations.const Curve animationCurve = Curves.fastEaseInToSlowEaseOut;final bool isCurrent = getIsCurrent();final bool animateForward;if (!isCurrent) {// If the page has already been navigated away from, then the animation// direction depends on whether or not it's still in the navigation stack,// regardless of velocity or drag position. For example, if a route is// being slowly dragged back by just a few pixels, but then a programmatic// pop occurs, the route should still be animated off the screen.// See https://github.com/flutter/flutter/issues/141268.animateForward = getIsActive();} else if (velocity.abs() >= _kMinFlingVelocity) {// If the user releases the page before mid screen with sufficient velocity,// or after mid screen, we should animate the page out. Otherwise, the page// should be animated back in.animateForward = velocity <= 0;} else {animateForward = controller.value > 0.5;}if (animateForward) {controller.animateTo(1.0,duration: _kDroppedSwipePageAnimationDuration,curve: animationCurve,);} else {if (isCurrent) {// This route is destined to pop at this point. Reuse navigator's pop.navigator.pop();}// The popping may have finished inline if already at the target destination.if (controller.isAnimating) {controller.animateBack(0.0,duration: _kDroppedSwipePageAnimationDuration,curve: animationCurve,);}}23 unmodified linesbegin: const _CupertinoEdgeShadowDecoration._(), // No decoration initially.end: const _CupertinoEdgeShadowDecoration._(// Eyeballed gradient used to mimic a drop shadow on the start side only.<Color>[Color(0x04000000), CupertinoColors.transparent],),);35 unmodified linesreturn a;}if (a == null) {return b!._colors == null? b: _CupertinoEdgeShadowDecoration._(b._colors!.map<Color>((Color color) => Color.lerp(null, color, t)!).toList(),);}if (b == null) {return a._colors == null? a: _CupertinoEdgeShadowDecoration._(a._colors.map<Color>((Color color) => Color.lerp(null, color, 1.0 - t)!).toList(),);}assert(b._colors != null || a._colors != null);// If it ever becomes necessary, we could allow decorations with different// length' here, similarly to how it is handled in [LinearGradient.lerp].assert(b._colors == null || a._colors == null || a._colors.length == b._colors.length);return _CupertinoEdgeShadowDecoration._(<Color>[for (int i = 0; i < b._colors!.length; i += 1) Color.lerp(a._colors?[i], b._colors[i], t)!,]);}@override13 unmodified lines}@override_CupertinoEdgeShadowPainter createBoxPainter([VoidCallback? onChanged]) {return _CupertinoEdgeShadowPainter(this, onChanged);}2 unmodified linesif (other.runtimeType != runtimeType) {return false;}return other is _CupertinoEdgeShadowDecoration && other._colors == _colors;}@override8 unmodified lines/// A [BoxPainter] used to draw the page transition shadow using gradients.class _CupertinoEdgeShadowPainter extends BoxPainter {_CupertinoEdgeShadowPainter(this._decoration, super.onChanged): assert(_decoration._colors == null || _decoration._colors.length > 1);final _CupertinoEdgeShadowDecoration _decoration;34 unmodified linesfinal TextDirection? textDirection = configuration.textDirection;assert(textDirection != null);final (double shadowDirection, double start) = switch (textDirection!) {TextDirection.rtl => (1, offset.dx + configuration.size!.width),TextDirection.ltr => (-1, offset.dx),};int bandColorIndex = 0;for (int dx = 0; dx < shadowWidth; dx += 1) {if (dx ~/ bandWidth != bandColorIndex) {bandColorIndex += 1;}final Paint paint =Paint()..color =Color.lerp(colors[bandColorIndex],colors[bandColorIndex + 1],(dx % bandWidth) / bandWidth,)!;final double x = start + shadowDirection * dx;canvas.drawRect(Rect.fromLTWH(x - 1.0, offset.dy, 1.0, shadowHeight), paint);}}}// The stiffness used by dialogs and action sheets.//// The stiffness value is obtained by examining the properties of// `CASpringAnimation` in Xcode. The damping value is derived similarly, with// additional precision calculated based on `_kStandardStiffness` to ensure a// damping ratio of 1 (critically damped): damping = 2 * sqrt(stiffness)const double _kStandardStiffness = 522.35;const double _kStandardDamping = 45.7099552;const SpringDescription _kStandardSpring = SpringDescription(mass: 1,stiffness: _kStandardStiffness,damping: _kStandardDamping,);// The iOS spring animation duration is 0.404 seconds, based on the properties// of `CASpringAnimation` in Xcode. At this point, the spring's position// `x(0.404)` is approximately 0.9990000, suggesting that iOS uses a position// tolerance of 1e-3 (matching the default `_epsilonDefault` value).//// However, the spring's velocity `dx(0.404)` is about 0.02, indicating that iOS// may not consider velocity when determining the animation's end condition. To// account for this, a larger velocity tolerance is applied here for added// safety.const Tolerance _kStandardTolerance = Tolerance(velocity: 0.03);/// A route that shows a modal iOS-style popup that slides up from the/// bottom of the screen.///39 unmodified linesbool semanticsDismissible = false,super.filter,super.settings,super.requestFocus,this.anchorPoint,}) : _barrierDismissible = barrierDismissible,_semanticsDismissible = semanticsDismissible;27 unmodified lines@overrideDuration get transitionDuration => _kModalPopupTransitionDuration;/// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}final Offset? anchorPoint;@overrideSimulation createSimulation({required bool forward}) {assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.');final double end = forward ? 1.0 : 0.0;return SpringSimulation(_kStandardSpring,controller!.value,end,0,tolerance: _kStandardTolerance,snapToEnd: true,);}@overrideWidget buildPage(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,) {return CupertinoUserInterfaceLevel(data: CupertinoUserInterfaceLevelData.elevated,child: DisplayFeatureSubScreen(anchorPoint: anchorPoint, child: Builder(builder: builder)),);}@overrideWidget buildTransitions(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,Widget child,) {return Align(alignment: Alignment.bottomCenter,child: FractionalTranslation(translation: _offsetTween.evaluate(animation), child: child),);}static final Tween<Offset> _offsetTween = Tween<Offset>(begin: const Offset(0.0, 1.0),end: Offset.zero,);}/// Shows a modal iOS-style popup that slides up from the bottom of the screen.29 unmodified lines/// [StatefulBuilder] or a custom [StatefulWidget] if the widget needs to/// update dynamically.////// The [requestFocus] parameter is used to specify whether the popup should/// request focus when shown./// {@macro flutter.widgets.navigator.Route.requestFocus}////// {@macro flutter.widgets.RawDialogRoute}////// Returns a `Future` that resolves to the value that was passed to35 unmodified linesbool semanticsDismissible = false,RouteSettings? routeSettings,Offset? anchorPoint,bool? requestFocus,}) {return Navigator.of(context, rootNavigator: useRootNavigator).push(CupertinoModalPopupRoute<T>(4 unmodified linessemanticsDismissible: semanticsDismissible,settings: routeSettings,anchorPoint: anchorPoint,requestFocus: requestFocus,),);}Widget _buildCupertinoDialogTransitions(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,Widget child,) {return child;}/// Displays an iOS-style dialog above the current contents of the app, with16 unmodified lines/// By default, `useRootNavigator` is `true` and the dialog route created by/// this method is pushed to the root navigator.////// {@macro flutter.material.dialog.requestFocus}/// {@macro flutter.widgets.navigator.Route.requestFocus}////// {@macro flutter.widgets.RawDialogRoute}////// If the application has multiple [Navigator] objects, it may be necessary to29 unmodified lines/// * [showGeneralDialog], which allows for customization of the dialog popup./// * [DisplayFeatureSubScreen], which documents the specifics of how/// [DisplayFeature]s can split the screen into sub-screens./// * <https://developer.apple.com/design/human-interface-guidelines/alerts/>Future<T?> showCupertinoDialog<T>({required BuildContext context,required WidgetBuilder builder,2 unmodified linesbool barrierDismissible = false,RouteSettings? routeSettings,Offset? anchorPoint,bool? requestFocus,}) {return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(CupertinoDialogRoute<T>(builder: builder,context: context,barrierDismissible: barrierDismissible,barrierLabel: barrierLabel,barrierColor: CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),settings: routeSettings,anchorPoint: anchorPoint,requestFocus: requestFocus,),);}/// A dialog route that shows an iOS-style dialog.43 unmodified linesString? barrierLabel,// This transition duration was eyeballed comparing with iOSsuper.transitionDuration = const Duration(milliseconds: 250),this.transitionBuilder,super.settings,super.requestFocus,super.anchorPoint,}) : super(pageBuilder: (BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,) {return builder(context);},transitionBuilder: transitionBuilder ?? _buildCupertinoDialogTransitions,barrierLabel: barrierLabel ?? CupertinoLocalizations.of(context).modalBarrierDismissLabel,barrierColor:barrierColor ?? CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),);/// Custom transition builderRouteTransitionsBuilder? transitionBuilder;CurvedAnimation? _fadeAnimation;@overrideSimulation createSimulation({required bool forward}) {assert(!debugTransitionCompleted(), 'Cannot reuse a $runtimeType after disposing it.');final double end = forward ? 1.0 : 0.0;return SpringSimulation(_kStandardSpring,controller!.value,end,0,tolerance: _kStandardTolerance,snapToEnd: true,);}@overrideWidget buildTransitions(BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,Widget child,) {if (transitionBuilder != null) {return super.buildTransitions(context, animation, secondaryAnimation, child);}if (animation.status == AnimationStatus.reverse) {return FadeTransition(opacity: animation, child: child);}return FadeTransition(opacity: animation,child: ScaleTransition(scale: animation.drive(_dialogScaleTween), child: child),);}@overridevoid dispose() {_fadeAnimation?.dispose();super.dispose();}// The curve and initial scale values were mostly eyeballed from iOS, however// they reuse the same animation curve that was modeled after native page// transitions.static final Tween<double> _dialogScaleTween = Tween<double>(begin: 1.3, end: 1.0);}
1 unmodified line23456773 unmodified lines81828384858641 unmodified lines12812913013113213313413513613713814 unmodified lines15315415515615715815914 unmodified lines1741751761771781791801811821831841852 unmodified lines1881891901911921931941951964 unmodified lines2012022032042052062072082092102112122132142152162171 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';73 unmodified linesthis.radiusWhileDragging = defaultRadiusWhileDragging,ScrollNotificationPredicate? notificationPredicate,super.scrollbarOrientation,}) : assert(thickness < double.infinity),assert(thicknessWhileDragging < double.infinity),super(41 unmodified lineslate AnimationController _thicknessAnimationController;double get _thickness {return widget.thickness! + _thicknessAnimationController.value * (widget.thicknessWhileDragging - widget.thickness!);}Radius get _radius {return Radius.lerp(widget.radius, widget.radiusWhileDragging, _thicknessAnimationController.value)!;}@override14 unmodified lines..color = CupertinoDynamicColor.resolve(_kScrollbarColor, context)..textDirection = Directionality.of(context)..thickness = _thickness..mainAxisMargin = _kScrollbarMainAxisMargin..crossAxisMargin = _kScrollbarCrossAxisMargin..radius = _radius..padding = MediaQuery.paddingOf(context)14 unmodified linesif (direction == null) {return;}switch (direction) {case Axis.vertical:_pressStartAxisPosition = localPosition.dy;case Axis.horizontal:_pressStartAxisPosition = localPosition.dx;}}@override2 unmodified linesreturn;}super.handleThumbPress();_thicknessAnimationController.forward().then<void>((_) => HapticFeedback.mediumImpact(),);}@override4 unmodified lines}_thicknessAnimationController.reverse();super.handleThumbPressEnd(localPosition, velocity);switch (direction) {case Axis.vertical:if (velocity.pixelsPerSecond.dy.abs() < 10 &&(localPosition.dy - _pressStartAxisPosition).abs() > 0) {HapticFeedback.mediumImpact();}case Axis.horizontal:if (velocity.pixelsPerSecond.dx.abs() < 10 &&(localPosition.dx - _pressStartAxisPosition).abs() > 0) {HapticFeedback.mediumImpact();}}}1 unmodified line234567891073 unmodified lines8485868788899041 unmodified lines13213313413513613713813914014114214314414514614714 unmodified lines16216316416516616716814 unmodified lines1831841851861871881891901911922 unmodified lines1951961971981992002014 unmodified lines2062072082092102112122132142152162172182192202212222232242251 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'package:flutter/material.dart';library;import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';73 unmodified linesthis.radiusWhileDragging = defaultRadiusWhileDragging,ScrollNotificationPredicate? notificationPredicate,super.scrollbarOrientation,super.mainAxisMargin = _kScrollbarMainAxisMargin,}) : assert(thickness < double.infinity),assert(thicknessWhileDragging < double.infinity),super(41 unmodified lineslate AnimationController _thicknessAnimationController;double get _thickness {return widget.thickness! +_thicknessAnimationController.value * (widget.thicknessWhileDragging - widget.thickness!);}Radius get _radius {return Radius.lerp(widget.radius,widget.radiusWhileDragging,_thicknessAnimationController.value,)!;}@override14 unmodified lines..color = CupertinoDynamicColor.resolve(_kScrollbarColor, context)..textDirection = Directionality.of(context)..thickness = _thickness..mainAxisMargin = widget.mainAxisMargin..crossAxisMargin = _kScrollbarCrossAxisMargin..radius = _radius..padding = MediaQuery.paddingOf(context)14 unmodified linesif (direction == null) {return;}_pressStartAxisPosition = switch (direction) {Axis.vertical => localPosition.dy,Axis.horizontal => localPosition.dx,};}@override2 unmodified linesreturn;}super.handleThumbPress();_thicknessAnimationController.forward().then<void>((_) => HapticFeedback.mediumImpact());}@override4 unmodified lines}_thicknessAnimationController.reverse();super.handleThumbPressEnd(localPosition, velocity);final (double axisPosition, double axisVelocity) = switch (direction) {Axis.horizontal => (localPosition.dx, velocity.pixelsPerSecond.dx),Axis.vertical => (localPosition.dy, velocity.pixelsPerSecond.dy),};if (axisPosition != _pressStartAxisPosition && axisVelocity.abs() < 10) {HapticFeedback.mediumImpact();}}@overridevoid handleTrackTapDown(TapDownDetails details) {// On iOS, tapping the track does not page towards the position of the tap.if (ScrollConfiguration.of(context).getPlatform(context) != TargetPlatform.iOS) {super.handleTrackTapDown(details);}}
12 unmodified lines13141516171893 unmodified lines1121131141151161171181191206 unmodified lines127128129130131132133134135136137138139140141142143144176 unmodified lines3213223233243253263273283293303313323333343353363373383393403413 unmodified lines34534634734834935015 unmodified lines3663673683693703717 unmodified lines37938038138238338438538638710 unmodified lines3983994004014024034044054064074084094104114124134144154164174184 unmodified lines4234244254264274284294304314324334344354364374384394404414424434444457 unmodified lines45345445545645745845946046146212 unmodified linesexport 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType;/// A [CupertinoTextField] that mimics the look and behavior of UIKit's/// `UISearchTextField`.///93 unmodified linesthis.padding = const EdgeInsetsDirectional.fromSTEB(5.5, 8, 5.5, 8),this.itemColor = CupertinoColors.secondaryLabel,this.itemSize = 20.0,this.prefixInsets = const EdgeInsetsDirectional.fromSTEB(6, 0, 0, 3),this.prefixIcon = const Icon(CupertinoIcons.search),this.suffixInsets = const EdgeInsetsDirectional.fromSTEB(0, 0, 5, 2),this.suffixIcon = const Icon(CupertinoIcons.xmark_circle_fill),this.suffixMode = OverlayVisibilityMode.editing,this.onSuffixTap,6 unmodified linesthis.onTap,this.autocorrect = true,this.enabled,}) : assert(!((decoration != null) && (backgroundColor != null)),'Cannot provide both a background color and a decoration\n''To provide both, use "decoration: BoxDecoration(color: ''backgroundColor)"',),assert(!((decoration != null) && (borderRadius != null)),'Cannot provide both a border radius and a decoration\n''To provide both, use "decoration: BoxDecoration(borderRadius: ''borderRadius)"',);/// Controls the text being edited.///176 unmodified lines/// respond to touch events including the [prefixIcon] and [suffixIcon] button.final bool? enabled;@overrideState<StatefulWidget> createState() => _CupertinoSearchTextFieldState();}class _CupertinoSearchTextFieldState extends State<CupertinoSearchTextField>with RestorationMixin {/// Default value for the border radius. Radius value was determined using the/// comparison tool in https://github.com/flutter/platform_tests/.final BorderRadius _kDefaultBorderRadius =const BorderRadius.all(Radius.circular(9.0));RestorableTextEditingController? _controller;TextEditingController get _effectiveController =>widget.controller ?? _controller!.value;@overridevoid initState() {3 unmodified lines}}@overridevoid didUpdateWidget(CupertinoSearchTextField oldWidget) {super.didUpdateWidget(oldWidget);15 unmodified lines@overridevoid dispose() {super.dispose();if (widget.controller == null) {_controller?.dispose();7 unmodified linesvoid _createLocalController([TextEditingValue? value]) {assert(_controller == null);_controller = value == null? RestorableTextEditingController(): RestorableTextEditingController.fromValue(value);if (!restorePending) {_registerController();}10 unmodified lines}}@overrideWidget build(BuildContext context) {final String placeholder = widget.placeholder ??CupertinoLocalizations.of(context).searchTextFieldPlaceholderLabel;final TextStyle placeholderStyle = widget.placeholderStyle ??const TextStyle(color: CupertinoColors.systemGrey);// The icon size will be scaled by a factor of the accessibility text scale,// to follow the behavior of `UISearchTextField`.final double scaledIconSize = MediaQuery.textScalerOf(context).textScaleFactor * widget.itemSize;// If decoration was not provided, create a decoration with the provided// background color and border radius.final BoxDecoration decoration = widget.decoration ??BoxDecoration(color: widget.backgroundColor ?? CupertinoColors.tertiarySystemFill,borderRadius: widget.borderRadius ?? _kDefaultBorderRadius,4 unmodified linessize: scaledIconSize,);final Widget prefix = Padding(padding: widget.prefixInsets,child: IconTheme(data: iconThemeData,child: widget.prefixIcon,),);final Widget suffix = Padding(padding: widget.suffixInsets,child: CupertinoButton(onPressed: widget.onSuffixTap ?? _defaultOnSuffixTap,minSize: 0,padding: EdgeInsets.zero,child: IconTheme(data: iconThemeData,child: widget.suffixIcon,),),);7 unmodified lineskeyboardType: widget.keyboardType,onTap: widget.onTap,enabled: widget.enabled ?? true,suffixMode: widget.suffixMode,placeholder: placeholder,placeholderStyle: placeholderStyle,padding: widget.padding,onChanged: widget.onChanged,onSubmitted: widget.onSubmitted,focusNode: widget.focusNode,12 unmodified lines13141516171819202122232493 unmodified lines1181191201211221231241251266 unmodified lines133134135136137138139140141142143144145146147148149150151152153154155176 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683 unmodified lines37237337437537637737837938038138238338438515 unmodified lines4014024034044054064074084094107 unmodified lines41841942042142242342442542642710 unmodified lines4384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964 unmodified lines5015025035045055065075085095105115125135145155165175185195205215225237 unmodified lines53153253353453553653753853954054154254354454512 unmodified linesexport 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType;// The fraction of the height of the search text field after which its contents// completely fade out when resized on scroll.//// Eyeballed on an iPhone 15 simulator running iOS 17.5.const double _kMinHeightBeforeTotalTransparency = 4 / 5;/// A [CupertinoTextField] that mimics the look and behavior of UIKit's/// `UISearchTextField`.///93 unmodified linesthis.padding = const EdgeInsetsDirectional.fromSTEB(5.5, 8, 5.5, 8),this.itemColor = CupertinoColors.secondaryLabel,this.itemSize = 20.0,this.prefixInsets = const EdgeInsetsDirectional.fromSTEB(6, 8, 0, 8),this.prefixIcon = const Icon(CupertinoIcons.search),this.suffixInsets = const EdgeInsetsDirectional.fromSTEB(0, 8, 5, 8),this.suffixIcon = const Icon(CupertinoIcons.xmark_circle_fill),this.suffixMode = OverlayVisibilityMode.editing,this.onSuffixTap,6 unmodified linesthis.onTap,this.autocorrect = true,this.enabled,this.cursorWidth = 2.0,this.cursorHeight,this.cursorRadius = const Radius.circular(2.0),this.cursorOpacityAnimates = true,this.cursorColor,}) : assert(!((decoration != null) && (backgroundColor != null)),'Cannot provide both a background color and a decoration\n''To provide both, use "decoration: BoxDecoration(color: ''backgroundColor)"',),assert(!((decoration != null) && (borderRadius != null)),'Cannot provide both a border radius and a decoration\n''To provide both, use "decoration: BoxDecoration(borderRadius: ''borderRadius)"',);/// Controls the text being edited.///176 unmodified lines/// respond to touch events including the [prefixIcon] and [suffixIcon] button.final bool? enabled;/// {@macro flutter.widgets.editableText.cursorWidth}final double cursorWidth;/// {@macro flutter.widgets.editableText.cursorHeight}final double? cursorHeight;/// {@macro flutter.widgets.editableText.cursorRadius}final Radius cursorRadius;/// {@macro flutter.widgets.editableText.cursorOpacityAnimates}final bool cursorOpacityAnimates;/// The color to use when painting the cursor.final Color? cursorColor;@overrideState<StatefulWidget> createState() => _CupertinoSearchTextFieldState();}class _CupertinoSearchTextFieldState extends State<CupertinoSearchTextField> with RestorationMixin {/// Default value for the border radius. Radius value was determined using the/// comparison tool in https://github.com/flutter/platform_tests/.final BorderRadius _kDefaultBorderRadius = const BorderRadius.all(Radius.circular(9.0));RestorableTextEditingController? _controller;TextEditingController get _effectiveController => widget.controller ?? _controller!.value;ScrollNotificationObserverState? _scrollNotificationObserver;double _fadeExtent = 0.0;double? _maxHeight;@overridevoid initState() {3 unmodified lines}}@overridevoid didChangeDependencies() {super.didChangeDependencies();_scrollNotificationObserver?.removeListener(_handleScrollNotification);_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);_scrollNotificationObserver?.addListener(_handleScrollNotification);}@overridevoid didUpdateWidget(CupertinoSearchTextField oldWidget) {super.didUpdateWidget(oldWidget);15 unmodified lines@overridevoid dispose() {if (_scrollNotificationObserver != null) {_scrollNotificationObserver!.removeListener(_handleScrollNotification);_scrollNotificationObserver = null;}super.dispose();if (widget.controller == null) {_controller?.dispose();7 unmodified linesvoid _createLocalController([TextEditingValue? value]) {assert(_controller == null);_controller =value == null? RestorableTextEditingController(): RestorableTextEditingController.fromValue(value);if (!restorePending) {_registerController();}10 unmodified lines}}void _handleScrollNotification(ScrollNotification notification) {if (_maxHeight == null) {_maxHeight ??= context.size?.height;} else if (notification is ScrollUpdateNotification) {final double currentHeight = context.size?.height ?? 0.0;setState(() {_fadeExtent = _calculateScrollOpacity(currentHeight, _maxHeight!);});}}static double _calculateScrollOpacity(double currentHeight, double maxHeight) {final double thresholdHeight = maxHeight * _kMinHeightBeforeTotalTransparency;if (currentHeight >= maxHeight) {return 0.0;} else if (currentHeight <= thresholdHeight) {return 1.0;} else {final double range = maxHeight - thresholdHeight;final double progress = (currentHeight - thresholdHeight) / range;return 1.0 - progress;}}// Animate the top padding so that the contents of the search field// move upwards when the search text field is resized on scroll.EdgeInsetsGeometry _animatedInsets(BuildContext context, EdgeInsetsGeometry insets) {final EdgeInsets currentInsets = insets.resolve(Directionality.of(context));final EdgeInsetsGeometry? animatedInsets = EdgeInsetsGeometry.lerp(insets,currentInsets.copyWith(top: currentInsets.top / 2),_fadeExtent,);return animatedInsets ?? insets;}@overrideWidget build(BuildContext context) {final String placeholder =widget.placeholder ?? CupertinoLocalizations.of(context).searchTextFieldPlaceholderLabel;final TextStyle placeholderStyle =widget.placeholderStyle ??TextStyle(color: CupertinoColors.systemGrey.withOpacity(1.0 - _fadeExtent));// The icon size will be scaled by a factor of the accessibility text scale,// to follow the behavior of `UISearchTextField`.final double scaledIconSize = MediaQuery.textScalerOf(context).scale(widget.itemSize);// If decoration was not provided, create a decoration with the provided// background color and border radius.final BoxDecoration decoration =widget.decoration ??BoxDecoration(color: widget.backgroundColor ?? CupertinoColors.tertiarySystemFill,borderRadius: widget.borderRadius ?? _kDefaultBorderRadius,4 unmodified linessize: scaledIconSize,);final Widget prefix = Opacity(opacity: 1.0 - _fadeExtent,child: Padding(padding: _animatedInsets(context, widget.prefixInsets),child: IconTheme(data: iconThemeData, child: widget.prefixIcon),),);final Widget suffix = Opacity(opacity: 1.0 - _fadeExtent,child: Padding(padding: _animatedInsets(context, widget.suffixInsets),child: CupertinoButton(onPressed: widget.onSuffixTap ?? _defaultOnSuffixTap,minSize: 0,padding: EdgeInsets.zero,child: IconTheme(data: iconThemeData, child: widget.suffixIcon),),),);7 unmodified lineskeyboardType: widget.keyboardType,onTap: widget.onTap,enabled: widget.enabled ?? true,cursorWidth: widget.cursorWidth,cursorHeight: widget.cursorHeight,cursorRadius: widget.cursorRadius,cursorOpacityAnimates: widget.cursorOpacityAnimates,cursorColor: widget.cursorColor,suffixMode: widget.suffixMode,placeholder: placeholder,placeholderStyle: placeholderStyle,padding: _animatedInsets(context, widget.padding),onChanged: widget.onChanged,onSubmitted: widget.onSubmitted,focusNode: widget.focusNode,
1 unmodified line23456710 unmodified lines18192021222333 unmodified lines575859606162636465666768697071727324 unmodified lines989910010110210310443 unmodified lines14814915015115215315415515615715813 unmodified lines1721731741751761771781791801811821833 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422557 unmodified lines28328428528628728828912 unmodified lines3023033043053063073083093103113123133144 unmodified lines31932032132232332417 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536627 unmodified lines39439539639739839940040140240342 unmodified lines44644744844945045145262 unmodified lines5155165175185195205216 unmodified lines5285295305315325335346 unmodified lines5415425435445455465476 unmodified lines55455555655755855956017 unmodified lines57857958058158258358441 unmodified lines62662762862963063118 unmodified lines65065165265365465565665765865966066166266366466566611 unmodified lines67867968068168268368468513 unmodified lines6997007017027037047057067077081 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:collection';import 'dart:math' as math;10 unmodified lines// Minimum height of the segmented control.const double _kMinSegmentedControlHeight = 28.0;// The duration of the fade animation used to transition when a new widget// is selected.const Duration _kFadeDuration = Duration(milliseconds: 165);33 unmodified lines/// A segmented control may optionally be created with custom colors. The/// [unselectedColor], [selectedColor], [borderColor], and [pressedColor]/// arguments can be used to override the segmented control's colors from/// [CupertinoTheme] defaults.////// {@tool dartpad}/// This example shows a [CupertinoSegmentedControl] with an enum type.////// The callback provided to [onValueChanged] should update the state of/// the parent [StatefulWidget] using the [State.setState] method, so that/// the parent gets rebuilt; for example:////// ** See code in examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart **/// {@end-tool}/// See also:////// * [CupertinoSegmentedControl], a segmented control widget in the style used24 unmodified linesthis.selectedColor,this.borderColor,this.pressedColor,this.padding,}) : assert(children.length >= 2),assert(groupValue == null || children.keys.any((T child) => child == groupValue),43 unmodified lines/// Defaults to the selectedColor at 20% opacity if null.final Color? pressedColor;/// The CupertinoSegmentedControl will be placed inside this padding.////// Defaults to EdgeInsets.symmetric(horizontal: 16.0)final EdgeInsetsGeometry? padding;@overrideState<CupertinoSegmentedControl<T>> createState() => _SegmentedControlState<T>();}13 unmodified linesColor? _unselectedColor;Color? _borderColor;Color? _pressedColor;AnimationController createAnimationController() {return AnimationController(duration: _kFadeDuration,vsync: this,)..addListener(() {setState(() {// State of background/text colors has changed});3 unmodified linesbool _updateColors() {assert(mounted, 'This should only be called after didUpdateDependencies');bool changed = false;final Color selectedColor = widget.selectedColor ?? CupertinoTheme.of(context).primaryColor;if (_selectedColor != selectedColor) {changed = true;_selectedColor = selectedColor;}final Color unselectedColor = widget.unselectedColor ?? CupertinoTheme.of(context).primaryContrastingColor;if (_unselectedColor != unselectedColor) {changed = true;_unselectedColor = unselectedColor;}final Color borderColor = widget.borderColor ?? CupertinoTheme.of(context).primaryColor;if (_borderColor != borderColor) {changed = true;_borderColor = borderColor;}final Color pressedColor = widget.pressedColor ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2);if (_pressedColor != pressedColor) {changed = true;_pressedColor = pressedColor;}_forwardBackgroundColorTween = ColorTween(begin: _pressedColor,end: _selectedColor,);_reverseBackgroundColorTween = ColorTween(begin: _unselectedColor,end: _selectedColor,);_textColorTween = ColorTween(begin: _selectedColor,end: _unselectedColor,);return changed;}57 unmodified linessuper.dispose();}void _onTapDown(T currentKey) {if (_pressedKey == null && currentKey != widget.groupValue) {setState(() {12 unmodified linesif (currentKey != _pressedKey) {return;}if (currentKey != widget.groupValue) {widget.onValueChanged(currentKey);}_pressedKey = null;}Color? getTextColor(int index, T currentKey) {if (_selectionControllers[index].isAnimating) {return _textColorTween.evaluate(_selectionControllers[index]);}4 unmodified lines}Color? getBackgroundColor(int index, T currentKey) {if (_selectionControllers[index].isAnimating) {return _childTweens[index].evaluate(_selectionControllers[index]);}17 unmodified linesselectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex;pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex;final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith(color: getTextColor(index, currentKey),);final IconThemeData iconTheme = IconThemeData(color: getTextColor(index, currentKey),);Widget child = Center(child: widget.children[currentKey],);child = MouseRegion(cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,child: GestureDetector(behavior: HitTestBehavior.opaque,onTapDown: (TapDownDetails event) {_onTapDown(currentKey);},onTapCancel: _onTapCancel,onTap: () {_onTap(currentKey);},27 unmodified linesreturn Padding(padding: widget.padding ?? _kHorizontalItemPadding,child: UnconstrainedBox(constrainedAxis: Axis.horizontal,child: box,),);}}42 unmodified linestypedef _NextChild = RenderBox? Function(RenderBox child);class _RenderSegmentedControl<T> extends RenderBoxwith ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {_RenderSegmentedControl({required int? selectedIndex,62 unmodified linesRenderBox? child = firstChild;double minWidth = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final double childWidth = child.getMinIntrinsicWidth(height);minWidth = math.max(minWidth, childWidth);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double maxWidth = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final double childWidth = child.getMaxIntrinsicWidth(height);maxWidth = math.max(maxWidth, childWidth);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double minHeight = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final double childHeight = child.getMinIntrinsicHeight(width);minHeight = math.max(minHeight, childHeight);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double maxHeight = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final double childHeight = child.getMaxIntrinsicHeight(width);maxHeight = math.max(maxHeight, childHeight);child = childParentData.nextSibling;17 unmodified linesRenderBox? child = leftChild;double start = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final Offset childOffset = Offset(start, 0.0);childParentData.offset = childOffset;final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height);41 unmodified linesreturn constraints.constrain(Size(childSize.width * childCount, childSize.height));}@overrideSize computeDryLayout(BoxConstraints constraints) {final Size childSize = _calculateChildSize(constraints);18 unmodified linesswitch (textDirection) {case TextDirection.rtl:_layoutRects(childBefore,lastChild,firstChild,);case TextDirection.ltr:_layoutRects(childAfter,firstChild,lastChild,);}size = _computeOverallSizeFromChildSize(childSize);11 unmodified lines}void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;context.canvas.drawRRect(childParentData.surroundingRect!.shift(offset),13 unmodified lines}@overridebool hitTestChildren(BoxHitTestResult result, { required Offset position }) {RenderBox? child = lastChild;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;if (childParentData.surroundingRect!.contains(position)) {return result.addWithPaintOffset(offset: childParentData.offset,1 unmodified line234567891010 unmodified lines21222324252627282933 unmodified lines636465666768697071727374757677787980818283848586878824 unmodified lines11311411511611711811912012112243 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019113 unmodified lines2052062072082092102112122132142152163 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326457 unmodified lines32232332432532632712 unmodified lines3403413423433443453463473483493503513523533543553563574 unmodified lines36236336436536636736836937017 unmodified lines38838939039139239339439539639739839940040140240340440540640740840941041127 unmodified lines43944044144244344444542 unmodified lines48848949049149249349449562 unmodified lines5585595605615625635645656 unmodified lines5725735745755765775785796 unmodified lines5865875885895905915925936 unmodified lines60060160260360460560660717 unmodified lines62562662762862963063163241 unmodified lines67467567667767867968068168268368468568668768868969069169269318 unmodified lines71271371471571671771871972011 unmodified lines73273373473573673773873913 unmodified lines7537547557567577587597607617627631 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'switch.dart';library;import 'dart:collection';import 'dart:math' as math;10 unmodified lines// Minimum height of the segmented control.const double _kMinSegmentedControlHeight = 28.0;// The default color used for the text of the disabled segment.const Color _kDisableTextColor = Color.fromARGB(115, 122, 122, 122);// The duration of the fade animation used to transition when a new widget// is selected.const Duration _kFadeDuration = Duration(milliseconds: 165);33 unmodified lines/// A segmented control may optionally be created with custom colors. The/// [unselectedColor], [selectedColor], [borderColor], and [pressedColor]/// arguments can be used to override the segmented control's colors from/// [CupertinoTheme] defaults. The [disabledColor] and [disabledTextColor]/// set the background and text colors of the segment when it is disabled.////// The segmented control can be disabled by adding children to the [Set] of/// [disabledChildren]. If the child is not present in the [Set], it is enabled/// by default.////// {@tool dartpad}/// This example shows a [CupertinoSegmentedControl] with an enum type.////// The callback provided to [onValueChanged] should update the state of/// the parent [StatefulWidget] using the [State.setState] method, so that/// the parent gets rebuilt.////// This example also demonstrates how to use the [disabledChildren] property by/// toggling each [CupertinoSwitch] to enable or disable the segments.////// ** See code in examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart **/// {@end-tool}////// See also:////// * [CupertinoSegmentedControl], a segmented control widget in the style used24 unmodified linesthis.selectedColor,this.borderColor,this.pressedColor,this.disabledColor,this.disabledTextColor,this.padding,this.disabledChildren = const <Never>{},}) : assert(children.length >= 2),assert(groupValue == null || children.keys.any((T child) => child == groupValue),43 unmodified lines/// Defaults to the selectedColor at 20% opacity if null.final Color? pressedColor;/// The color used to fill the background of the segment when it is disabled.////// If null, this color will be 50% opacity of the [selectedColor] when/// the segment is selected. If the segment is unselected, this color will be/// set to [unselectedColor].final Color? disabledColor;/// The color used for the text of the segment when it is disabled.final Color? disabledTextColor;/// The CupertinoSegmentedControl will be placed inside this padding.////// Defaults to EdgeInsets.symmetric(horizontal: 16.0)final EdgeInsetsGeometry? padding;/// The set of identifying keys that correspond to the segments that should be disabled.////// All segments are enabled by default.final Set<T> disabledChildren;@overrideState<CupertinoSegmentedControl<T>> createState() => _SegmentedControlState<T>();}13 unmodified linesColor? _unselectedColor;Color? _borderColor;Color? _pressedColor;Color? _selectedDisabledColor;Color? _unselectedDisabledColor;Color? _disabledTextColor;AnimationController createAnimationController() {return AnimationController(duration: _kFadeDuration, vsync: this)..addListener(() {setState(() {// State of background/text colors has changed});3 unmodified linesbool _updateColors() {assert(mounted, 'This should only be called after didUpdateDependencies');bool changed = false;final Color disabledTextColor = widget.disabledTextColor ?? _kDisableTextColor;if (_disabledTextColor != disabledTextColor) {changed = true;_disabledTextColor = disabledTextColor;}final Color selectedColor = widget.selectedColor ?? CupertinoTheme.of(context).primaryColor;if (_selectedColor != selectedColor) {changed = true;_selectedColor = selectedColor;}final Color unselectedColor =widget.unselectedColor ?? CupertinoTheme.of(context).primaryContrastingColor;if (_unselectedColor != unselectedColor) {changed = true;_unselectedColor = unselectedColor;}final Color selectedDisabledColor = widget.disabledColor ?? selectedColor.withOpacity(0.5);final Color unselectedDisabledColor = widget.disabledColor ?? unselectedColor;if (_selectedDisabledColor != selectedDisabledColor ||_unselectedDisabledColor != unselectedDisabledColor) {changed = true;_selectedDisabledColor = selectedDisabledColor;_unselectedDisabledColor = unselectedDisabledColor;}final Color borderColor = widget.borderColor ?? CupertinoTheme.of(context).primaryColor;if (_borderColor != borderColor) {changed = true;_borderColor = borderColor;}final Color pressedColor =widget.pressedColor ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2);if (_pressedColor != pressedColor) {changed = true;_pressedColor = pressedColor;}_forwardBackgroundColorTween = ColorTween(begin: _pressedColor, end: _selectedColor);_reverseBackgroundColorTween = ColorTween(begin: _unselectedColor, end: _selectedColor);_textColorTween = ColorTween(begin: _selectedColor, end: _unselectedColor);return changed;}57 unmodified linessuper.dispose();}void _onTapDown(T currentKey) {if (_pressedKey == null && currentKey != widget.groupValue) {setState(() {12 unmodified linesif (currentKey != _pressedKey) {return;}if (!widget.disabledChildren.contains(currentKey)) {if (currentKey != widget.groupValue) {widget.onValueChanged(currentKey);}}_pressedKey = null;}Color? getTextColor(int index, T currentKey) {if (widget.disabledChildren.contains(currentKey)) {return _disabledTextColor;}if (_selectionControllers[index].isAnimating) {return _textColorTween.evaluate(_selectionControllers[index]);}4 unmodified lines}Color? getBackgroundColor(int index, T currentKey) {if (widget.disabledChildren.contains(currentKey)) {return widget.groupValue == currentKey ? _selectedDisabledColor : _unselectedDisabledColor;}if (_selectionControllers[index].isAnimating) {return _childTweens[index].evaluate(_selectionControllers[index]);}17 unmodified linesselectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex;pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex;final TextStyle textStyle = DefaultTextStyle.of(context,).style.copyWith(color: getTextColor(index, currentKey));final IconThemeData iconTheme = IconThemeData(color: getTextColor(index, currentKey));Widget child = Center(child: widget.children[currentKey]);child = MouseRegion(cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,child: GestureDetector(behavior: HitTestBehavior.opaque,onTapDown:widget.disabledChildren.contains(currentKey)? null: (TapDownDetails event) {_onTapDown(currentKey);},onTapCancel: widget.disabledChildren.contains(currentKey) ? null : _onTapCancel,onTap: () {_onTap(currentKey);},27 unmodified linesreturn Padding(padding: widget.padding ?? _kHorizontalItemPadding,child: UnconstrainedBox(constrainedAxis: Axis.horizontal, child: box),);}}42 unmodified linestypedef _NextChild = RenderBox? Function(RenderBox child);class _RenderSegmentedControl<T> extends RenderBoxwithContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {_RenderSegmentedControl({required int? selectedIndex,62 unmodified linesRenderBox? child = firstChild;double minWidth = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final double childWidth = child.getMinIntrinsicWidth(height);minWidth = math.max(minWidth, childWidth);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double maxWidth = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final double childWidth = child.getMaxIntrinsicWidth(height);maxWidth = math.max(maxWidth, childWidth);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double minHeight = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final double childHeight = child.getMinIntrinsicHeight(width);minHeight = math.max(minHeight, childHeight);child = childParentData.nextSibling;6 unmodified linesRenderBox? child = firstChild;double maxHeight = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final double childHeight = child.getMaxIntrinsicHeight(width);maxHeight = math.max(maxHeight, childHeight);child = childParentData.nextSibling;17 unmodified linesRenderBox? child = leftChild;double start = 0.0;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final Offset childOffset = Offset(start, 0.0);childParentData.offset = childOffset;final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height);41 unmodified linesreturn constraints.constrain(Size(childSize.width * childCount, childSize.height));}@overridedouble? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {final Size childSize = _calculateChildSize(constraints);final BoxConstraints childConstraints = BoxConstraints.tight(childSize);BaselineOffset baselineOffset = BaselineOffset.noBaseline;for (RenderBox? child = firstChild; child != null; child = childAfter(child)) {baselineOffset = baselineOffset.minOf(BaselineOffset(child.getDryBaseline(childConstraints, baseline)),);}return baselineOffset.offset;}@overrideSize computeDryLayout(BoxConstraints constraints) {final Size childSize = _calculateChildSize(constraints);18 unmodified linesswitch (textDirection) {case TextDirection.rtl:_layoutRects(childBefore, lastChild, firstChild);case TextDirection.ltr:_layoutRects(childAfter, firstChild, lastChild);}size = _computeOverallSizeFromChildSize(childSize);11 unmodified lines}void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;context.canvas.drawRRect(childParentData.surroundingRect!.shift(offset),13 unmodified lines}@overridebool hitTestChildren(BoxHitTestResult result, {required Offset position}) {RenderBox? child = lastChild;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;if (childParentData.surroundingRect!.contains(position)) {return result.addWithPaintOffset(offset: childParentData.offset,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825// Copyright 2014 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
import 'package:flutter/gestures.dart';import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';
import 'colors.dart';import 'interface_level.dart';import 'route.dart';import 'theme.dart';
// Smoothing factor applied to the device's top padding (which approximates the corner radius)// to achieve a smoother end to the corner radius animation. A value of 1.0 would use// the full top padding. Values less than 1.0 reduce the effective corner radius, improving// the animation's appearance. Determined through empirical testing.const double _kDeviceCornerRadiusSmoothingFactor = 0.9;
// Threshold in logical pixels. If the calculated device corner radius (after applying// the smoothing factor) is below this value, the corner radius transition animation will// start from zero. This prevents abrupt transitions for devices with small or negligible// corner radii. This value, combined with the smoothing factor, corresponds roughly// to double the targeted radius of 12. Determined through testing and visual inspection.const double _kRoundedDeviceCornersThreshold = 20.0;
// The distance from the top of the open sheet to the top of the screen, as a ratio// of the total height of the screen. Found from eyeballing a simulator running// iOS 18.0.const double _kTopGapRatio = 0.08;
// Tween for animating a Cupertino sheet onto the screen.//// Begins fully offscreen below the screen and ends onscreen with a small gap at// the top of the screen. Values found from eyeballing a simulator running iOS 18.0.final Animatable<Offset> _kBottomUpTween = Tween<Offset>( begin: const Offset(0.0, 1.0), end: const Offset(0.0, _kTopGapRatio),);
// Offset change for when a new sheet covers another sheet. '0.0' represents the// top of the space available for the new sheet, but because the previous sheet// was lowered slightly, the new sheet needs to go slightly higher than that.// Values found from eyeballing a simulator running iOS 18.0.final Animatable<Offset> _kBottomUpTweenWhenCoveringOtherSheet = Tween<Offset>( begin: const Offset(0.0, 1.0), end: const Offset(0.0, -0.02),);
// Tween that animates a sheet slightly up when it is covered by a new sheet.// Values found from eyeballing a simulator running iOS 18.0.final Animatable<Offset> _kMidUpTween = Tween<Offset>( begin: Offset.zero, end: const Offset(0.0, -0.005),);
// Offset from top of screen to slightly down when a fullscreen page is covered// by a sheet. Values found from eyeballing a simulator running iOS 18.0.final Animatable<Offset> _kTopDownTween = Tween<Offset>( begin: Offset.zero, end: const Offset(0.0, 0.07),);
// Opacity of the overlay color put over the sheet as it moves into the background.// Used to distinguish the sheet from the background. Value derived from eyeballing// a simulator running iOS 18.0.final Animatable<double> _kOpacityTween = Tween<double>(begin: 0.0, end: 0.10);
// The minimum velocity needed for a drag downwards to dismiss the sheet. Eyeballed// from a comparison against a simulator running iOS 18.0.const double _kMinFlingVelocity = 2.0; // Screen heights per second.
// The duration for a page to animate when the user releases it mid-swipe. Eyeballed// from a comparison against a simulator running iOS 18.0.const Duration _kDroppedSheetDragAnimationDuration = Duration(milliseconds: 300);
// Amount the sheet in the background scales down. Found by measuring the width// of the sheet in the background and comparing against the screen width on the// iOS simulator showing an iPhone 16 pro running iOS 18.0. The scale transition// will go from a default of 1.0 to 1.0 - _kSheetScaleFactor.const double _kSheetScaleFactor = 0.0835;
final Animatable<double> _kScaleTween = Tween<double>(begin: 1.0, end: 1.0 - _kSheetScaleFactor);
/// Shows a Cupertino-style sheet widget that slides up from the bottom of the/// screen and stacks the previous route behind the new sheet.////// This is a convenience method for displaying [CupertinoSheetRoute] for common,/// straightforward use cases. The Widget returned from `pageBuilder` will be/// used to display the content on the [CupertinoSheetRoute].////// `useNestedNavigation` allows new routes to be pushed inside of a [CupertinoSheetRoute]/// by adding a new [Navigator] inside of the [CupertinoSheetRoute].////// When `useNestedNavigation` is set to `true`, any route pushed to the stack/// from within the context of the [CupertinoSheetRoute] will display within that/// sheet. System back gestures and programatic pops on the initial route in a/// sheet will also be intercepted to pop the whole [CupertinoSheetRoute]. If/// a custom [Navigator] setup is needed, like for example to enable named routes/// or the pages API, then it is recommended to directly push a [CupertinoSheetRoute]/// to the stack with whatever configuration needed. See [CupertinoSheetRoute] for/// an example that manually sets up nested navigation.////// The whole sheet can be popped at once by either dragging down on the sheet,/// or calling [CupertinoSheetRoute.popSheet].////// When `enableDrag` is set to `true` (the default), users can dismiss the sheet/// by dragging it down or by calling [CupertinoSheetRoute.popSheet]. When/// `enableDrag` is `false`, users cannot dismiss the sheet by dragging, and it/// can only be closed by calling [CupertinoSheetRoute.popSheet].////// iOS sheet widgets are generally designed to be tightly coupled to the context/// of the widget that opened the sheet. As such, it is not recommended to push/// a non-sheet route that covers the sheet without first popping the sheet. If/// necessary however, it can be done by pushing to the root [Navigator].////// If `useNestedNavigation` is `false` (the default), then a [CupertinoSheetRoute]/// will be shown with no [Navigator] widget. Multiple calls to `showCupertinoSheet`/// can still be made to show multiple stacked sheets, if desired.////// `showCupertinoSheet` always pushes the [CupertinoSheetRoute] to the root/// [Navigator]. This is to ensure the previous route animates correctly.////// Returns a [Future] that resolves to the value (if any) that was passed to/// [Navigator.pop] when the sheet was closed.////// {@tool dartpad}/// This example shows how to navigate to use [showCupertinoSheet] to display a/// Cupertino sheet widget with nested navigation.////// ** See code in examples/api/lib/cupertino/sheet/cupertino_sheet.1.dart **/// {@end-tool}////// See also:////// * [CupertinoSheetRoute] the basic route version of the sheet view./// * [showCupertinoDialog] which displays an iOS-styled dialog./// * <https://developer.apple.com/design/human-interface-guidelines/sheets>Future<T?> showCupertinoSheet<T>({ required BuildContext context, required WidgetBuilder pageBuilder, bool useNestedNavigation = false, bool enableDrag = true,}) { final WidgetBuilder builder; final GlobalKey<NavigatorState> nestedNavigatorKey = GlobalKey<NavigatorState>(); if (!useNestedNavigation) { builder = pageBuilder; } else { builder = (BuildContext context) { return NavigatorPopHandler( onPopWithResult: (T? result) { nestedNavigatorKey.currentState!.maybePop(); }, child: Navigator( key: nestedNavigatorKey, initialRoute: '/', onGenerateInitialRoutes: (NavigatorState navigator, String initialRouteName) { return <Route<void>>[ CupertinoPageRoute<void>( builder: (BuildContext context) { return PopScope( canPop: false, onPopInvokedWithResult: (bool didPop, Object? result) { if (didPop) { return; } Navigator.of(context, rootNavigator: true).pop(result); }, child: pageBuilder(context), ); }, ), ]; }, ), ); }; }
return Navigator.of( context, rootNavigator: true, ).push<T>(CupertinoSheetRoute<T>(builder: builder, enableDrag: enableDrag));}
/// Provides an iOS-style sheet transition.////// The page slides up and stops below the top of the screen. When covered by/// another sheet view, it will slide slightly up and scale down to appear/// stacked behind the new sheet.class CupertinoSheetTransition extends StatefulWidget { /// Creates an iOS style sheet transition. const CupertinoSheetTransition({ super.key, required this.primaryRouteAnimation, required this.secondaryRouteAnimation, required this.child, required this.linearTransition, });
/// `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0 when /// this screen is being pushed. final Animation<double> primaryRouteAnimation;
/// `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0 when /// another screen is being pushed on top of this one. final Animation<double> secondaryRouteAnimation;
/// The widget below this widget in the tree. final Widget child;
/// Whether to perform the transition linearly. /// /// Used to respond to a drag gesture. final bool linearTransition;
/// The primary delegated transition. Will slide a non [CupertinoSheetRoute] page down. /// /// Provided to the previous route to coordinate transitions between routes. /// /// If a [CupertinoSheetRoute] already exists in the stack, then it will /// slide the previous sheet upwards instead. static Widget delegateTransition( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, bool allowSnapshotting, Widget? child, ) { if (CupertinoSheetRoute.hasParentSheet(context)) { return _delegatedCoverSheetSecondaryTransition(secondaryAnimation, child); } final bool linear = Navigator.of(context).userGestureInProgress;
final Curve curve = linear ? Curves.linear : Curves.linearToEaseOut; final Curve reverseCurve = linear ? Curves.linear : Curves.easeInToLinear; final CurvedAnimation curvedAnimation = CurvedAnimation( curve: curve, reverseCurve: reverseCurve, parent: secondaryAnimation, );
final double deviceCornerRadius = (MediaQuery.maybeViewPaddingOf(context)?.top ?? 0) * _kDeviceCornerRadiusSmoothingFactor; final bool roundedDeviceCorners = deviceCornerRadius > _kRoundedDeviceCornersThreshold;
final Animatable<BorderRadiusGeometry> decorationTween = Tween<BorderRadiusGeometry>( begin: BorderRadius.vertical( top: Radius.circular(roundedDeviceCorners ? deviceCornerRadius : 0), ), end: BorderRadius.circular(12), );
final Animation<BorderRadiusGeometry> radiusAnimation = curvedAnimation.drive(decorationTween); final Animation<double> opacityAnimation = curvedAnimation.drive(_kOpacityTween); final Animation<Offset> slideAnimation = curvedAnimation.drive(_kTopDownTween); final Animation<double> scaleAnimation = curvedAnimation.drive(_kScaleTween); curvedAnimation.dispose();
final bool isDarkMode = CupertinoTheme.brightnessOf(context) == Brightness.dark; final Color overlayColor = isDarkMode ? const Color(0xFFc8c8c8) : const Color(0xFF000000);
final Widget? contrastedChild = child != null && !secondaryAnimation.isDismissed ? Stack( children: <Widget>[ child, FadeTransition( opacity: opacityAnimation, child: ColoredBox(color: overlayColor, child: const SizedBox.expand()), ), ], ) : child;
return SlideTransition( position: slideAnimation, child: ScaleTransition( scale: scaleAnimation, filterQuality: FilterQuality.medium, alignment: Alignment.topCenter, child: AnimatedBuilder( animation: radiusAnimation, child: child, builder: (BuildContext context, Widget? child) { return ClipRRect( borderRadius: !secondaryAnimation.isDismissed ? radiusAnimation.value : BorderRadius.circular(0), child: contrastedChild, ); }, ), ), ); }
static Widget _delegatedCoverSheetSecondaryTransition( Animation<double> secondaryAnimation, Widget? child, ) { const Curve curve = Curves.linearToEaseOut; const Curve reverseCurve = Curves.easeInToLinear; final CurvedAnimation curvedAnimation = CurvedAnimation( curve: curve, reverseCurve: reverseCurve, parent: secondaryAnimation, );
final Animation<Offset> slideAnimation = curvedAnimation.drive(_kMidUpTween); final Animation<double> scaleAnimation = curvedAnimation.drive(_kScaleTween); curvedAnimation.dispose();
return SlideTransition( position: slideAnimation, transformHitTests: false, child: ScaleTransition( scale: scaleAnimation, filterQuality: FilterQuality.medium, alignment: Alignment.topCenter, child: ClipRRect( borderRadius: const BorderRadius.vertical(top: Radius.circular(12)), child: child, ), ), ); }
@override State<CupertinoSheetTransition> createState() => _CupertinoSheetTransitionState();}
class _CupertinoSheetTransitionState extends State<CupertinoSheetTransition> { // The offset animation when this page is being covered by another sheet. late Animation<Offset> _secondaryPositionAnimation;
// The scale animation when this page is being covered by another sheet. late Animation<double> _secondaryScaleAnimation;
// Curve of primary page which is coming in to cover another route. CurvedAnimation? _primaryPositionCurve;
// Curve of secondary page which is becoming covered by another sheet. CurvedAnimation? _secondaryPositionCurve;
@override void initState() { super.initState(); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle( statusBarBrightness: Brightness.dark, statusBarIconBrightness: Brightness.light, ), ); _setupAnimation(); }
@override void didUpdateWidget(covariant CupertinoSheetTransition oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.primaryRouteAnimation != widget.primaryRouteAnimation || oldWidget.secondaryRouteAnimation != widget.secondaryRouteAnimation) { _disposeCurve(); _setupAnimation(); } }
@override void dispose() { _disposeCurve(); super.dispose(); }
void _setupAnimation() { _primaryPositionCurve = CurvedAnimation( curve: Curves.fastEaseInToSlowEaseOut, reverseCurve: Curves.fastEaseInToSlowEaseOut.flipped, parent: widget.primaryRouteAnimation, ); _secondaryPositionCurve = CurvedAnimation( curve: Curves.linearToEaseOut, reverseCurve: Curves.easeInToLinear, parent: widget.secondaryRouteAnimation, ); _secondaryPositionAnimation = _secondaryPositionCurve!.drive(_kMidUpTween); _secondaryScaleAnimation = _secondaryPositionCurve!.drive(_kScaleTween); }
void _disposeCurve() { _primaryPositionCurve?.dispose(); _secondaryPositionCurve?.dispose(); _primaryPositionCurve = null; _secondaryPositionCurve = null; }
Widget _coverSheetPrimaryTransition( BuildContext context, Animation<double> animation, bool linearTransition, Widget? child, ) { final Animatable<Offset> offsetTween = CupertinoSheetRoute.hasParentSheet(context) ? _kBottomUpTweenWhenCoveringOtherSheet : _kBottomUpTween;
final CurvedAnimation curvedAnimation = CurvedAnimation( parent: animation, curve: linearTransition ? Curves.linear : Curves.fastEaseInToSlowEaseOut, reverseCurve: linearTransition ? Curves.linear : Curves.fastEaseInToSlowEaseOut.flipped, );
final Animation<Offset> positionAnimation = curvedAnimation.drive(offsetTween);
curvedAnimation.dispose();
return SlideTransition(position: positionAnimation, child: child); }
Widget _coverSheetSecondaryTransition(Animation<double> secondaryAnimation, Widget? child) { return SlideTransition( position: _secondaryPositionAnimation, transformHitTests: false, child: ScaleTransition( scale: _secondaryScaleAnimation, filterQuality: FilterQuality.medium, alignment: Alignment.topCenter, child: ClipRRect( borderRadius: const BorderRadius.vertical(top: Radius.circular(12)), child: child, ), ), ); }
@override Widget build(BuildContext context) { return SizedBox.expand( child: _coverSheetSecondaryTransition( widget.secondaryRouteAnimation, _coverSheetPrimaryTransition( context, widget.primaryRouteAnimation, widget.linearTransition, ClipRRect( borderRadius: const BorderRadius.vertical(top: Radius.circular(12)), child: widget.child, ), ), ), ); }}
/// Route for displaying an iOS sheet styled page.////// The `CupertinoSheetRoute` will slide up from the bottom of the screen and stop/// below the top of the screen. If the previous route is a non-sheet route, then/// it will animate downwards to stack behind the new sheet. If the previous route/// is a sheet route, then it will animate slightly upwards to look like it is laying/// on top of the previous stack of sheets.////// Typically called by [showCupertinoSheet], which provides some boilerplate for/// pushing the `CupertinoSheetRoute` to the root navigator and providing simple/// nested navigation.////// The sheet will be dismissed by dragging downwards on the screen, or a call to/// [CupertinoSheetRoute.popSheet].////// {@tool dartpad}/// This example shows how to navigate to [CupertinoSheetRoute] by using it the/// same as a regular route.////// ** See code in examples/api/lib/cupertino/sheet/cupertino_sheet.0.dart **/// {@end-tool}////// {@tool dartpad}/// This example shows how to show a Cupertino Sheet with nested navigation manually/// set up in order to enable restorable state.////// ** See code in examples/api/lib/cupertino/sheet/cupertino_sheet.2.dart **/// {@end-tool}////// See also:/// * [showCupertinoSheet], which is a convenience method for pushing a/// `CupertinoSheetRoute`, with optional nested navigation built in.class CupertinoSheetRoute<T> extends PageRoute<T> with _CupertinoSheetRouteTransitionMixin<T> { /// Creates a page route that displays an iOS styled sheet. CupertinoSheetRoute({super.settings, required this.builder, this.enableDrag = true});
/// Builds the primary contents of the sheet route. final WidgetBuilder builder;
@override final bool enableDrag;
@override Widget buildContent(BuildContext context) { final double bottomPadding = MediaQuery.sizeOf(context).height * _kTopGapRatio; return MediaQuery.removePadding( context: context, removeTop: true, removeBottom: true, child: Padding( padding: EdgeInsets.only(bottom: bottomPadding), child: CupertinoUserInterfaceLevel( data: CupertinoUserInterfaceLevelData.elevated, child: _CupertinoSheetScope(child: builder(context)), ), ), ); }
/// Checks if a Cupertino sheet view exists in the widget tree above the current /// context. static bool hasParentSheet(BuildContext context) { return _CupertinoSheetScope.maybeOf(context) != null; }
/// Pops the entire [CupertinoSheetRoute], if a sheet route exists in the stack. /// /// Used if to pop an entire sheet at once, if there is nested navigtion within /// that sheet. static void popSheet(BuildContext context) { if (hasParentSheet(context)) { Navigator.of(context, rootNavigator: true).pop(); } }
@override Color? get barrierColor => CupertinoColors.transparent;
@override bool get barrierDismissible => false;
@override String? get barrierLabel => null;
@override bool get maintainState => true;
@override bool get opaque => false;}
// Internally used to see if another sheet is in the tree already.class _CupertinoSheetScope extends InheritedWidget { const _CupertinoSheetScope({required super.child});
static _CupertinoSheetScope? maybeOf(BuildContext context) { return context.getInheritedWidgetOfExactType<_CupertinoSheetScope>(); }
@override bool updateShouldNotify(_CupertinoSheetScope oldWidget) => false;}
/// A mixin that replaces the entire screen with an iOS sheet transition for a/// [PageRoute].////// See also:////// * [CupertinoSheetRoute], which is a [PageRoute] that leverages this mixin.mixin _CupertinoSheetRouteTransitionMixin<T> on PageRoute<T> { /// Builds the primary contents of the route. @protected Widget buildContent(BuildContext context);
@override Duration get transitionDuration => const Duration(milliseconds: 500);
@override DelegatedTransitionBuilder? get delegatedTransition => CupertinoSheetTransition.delegateTransition;
/// Determines whether the content can be dragged. /// /// If `true`, dragging is enabled; otherwise, it remains fixed. bool get enableDrag;
@override Widget buildPage( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return buildContent(context); }
static _CupertinoDownGestureController<T> _startPopGesture<T>(ModalRoute<T> route) { return _CupertinoDownGestureController<T>( navigator: route.navigator!, getIsCurrent: () => route.isCurrent, getIsActive: () => route.isActive, controller: route.controller!, // protected access ); }
/// Returns a [CupertinoSheetTransition]. static Widget buildPageTransitions<T>( ModalRoute<T> route, BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, bool enableDrag, ) { final bool linearTransition = route.popGestureInProgress; return CupertinoSheetTransition( primaryRouteAnimation: animation, secondaryRouteAnimation: secondaryAnimation, linearTransition: linearTransition, child: _CupertinoDownGestureDetector<T>( enabledCallback: () => enableDrag, onStartPopGesture: () => _startPopGesture<T>(route), child: child, ), ); }
@override bool canTransitionTo(TransitionRoute<dynamic> nextRoute) { return nextRoute is _CupertinoSheetRouteTransitionMixin; }
@override Widget buildTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { return buildPageTransitions<T>(this, context, animation, secondaryAnimation, child, enableDrag); }}
class _CupertinoDownGestureDetector<T> extends StatefulWidget { const _CupertinoDownGestureDetector({ super.key, required this.enabledCallback, required this.onStartPopGesture, required this.child, });
final Widget child;
final ValueGetter<bool> enabledCallback;
final ValueGetter<_CupertinoDownGestureController<T>> onStartPopGesture;
@override _CupertinoDownGestureDetectorState<T> createState() => _CupertinoDownGestureDetectorState<T>();}
class _CupertinoDownGestureDetectorState<T> extends State<_CupertinoDownGestureDetector<T>> { _CupertinoDownGestureController<T>? _downGestureController;
late VerticalDragGestureRecognizer _recognizer;
@override void initState() { super.initState(); _recognizer = VerticalDragGestureRecognizer(debugOwner: this) ..onStart = _handleDragStart ..onUpdate = _handleDragUpdate ..onEnd = _handleDragEnd ..onCancel = _handleDragCancel; }
@override void dispose() { _recognizer.dispose();
// If this is disposed during a drag, call navigator.didStopUserGesture. if (_downGestureController != null) { WidgetsBinding.instance.addPostFrameCallback((_) { if (_downGestureController?.navigator.mounted ?? false) { _downGestureController?.navigator.didStopUserGesture(); } _downGestureController = null; }); } super.dispose(); }
void _handleDragStart(DragStartDetails details) { assert(mounted); assert(_downGestureController == null); _downGestureController = widget.onStartPopGesture(); }
void _handleDragUpdate(DragUpdateDetails details) { assert(mounted); assert(_downGestureController != null); _downGestureController!.dragUpdate( // Divide by size of the sheet. details.primaryDelta! / (context.size!.height - (context.size!.height * _kTopGapRatio)), ); }
void _handleDragEnd(DragEndDetails details) { assert(mounted); assert(_downGestureController != null); _downGestureController!.dragEnd(details.velocity.pixelsPerSecond.dy / context.size!.height); _downGestureController = null; }
void _handleDragCancel() { assert(mounted); // This can be called even if start is not called, paired with the "down" event // that we don't consider here. _downGestureController?.dragEnd(0.0); _downGestureController = null; }
void _handlePointerDown(PointerDownEvent event) { if (widget.enabledCallback()) { _recognizer.addPointer(event); } }
@override Widget build(BuildContext context) { return Listener( onPointerDown: _handlePointerDown, behavior: HitTestBehavior.translucent, child: widget.child, ); }}
class _CupertinoDownGestureController<T> { /// Creates a controller for an iOS-style back gesture. _CupertinoDownGestureController({ required this.navigator, required this.controller, required this.getIsActive, required this.getIsCurrent, }) { navigator.didStartUserGesture(); }
final AnimationController controller; final NavigatorState navigator; final ValueGetter<bool> getIsActive; final ValueGetter<bool> getIsCurrent;
/// The drag gesture has changed by [delta]. The total range of the drag /// should be 0.0 to 1.0. void dragUpdate(double delta) { controller.value -= delta; }
/// The drag gesture has ended with a vertical motion of [velocity] as a /// fraction of screen height per second. void dragEnd(double velocity) { // Fling in the appropriate direction. // // This curve has been determined through rigorously eyeballing native iOS // animations on a simulator running iOS 18.0. const Curve animationCurve = Curves.easeOut; final bool isCurrent = getIsCurrent(); final bool animateForward;
if (!isCurrent) { // If the page has already been navigated away from, then the animation // direction depends on whether or not it's still in the navigation stack, // regardless of velocity or drag position. For example, if a route is // being slowly dragged back by just a few pixels, but then a programmatic // pop occurs, the route should still be animated off the screen. // See https://github.com/flutter/flutter/issues/141268. animateForward = getIsActive(); } else if (velocity.abs() >= _kMinFlingVelocity) { // If the user releases the page before mid screen with sufficient velocity, // or after mid screen, we should animate the page out. Otherwise, the page // should be animated back in. animateForward = velocity <= 0; } else { // If the drag is dropped with low velocity, the sheet will pop if the // the drag goes a little past the halfway point on the screen. This is // eyeballed on a simulator running iOS 18.0. animateForward = controller.value > 0.52; }
if (animateForward) { controller.animateTo( 1.0, duration: _kDroppedSheetDragAnimationDuration, curve: animationCurve, ); } else { if (isCurrent) { // This route is destined to pop at this point. Reuse navigator's pop. final NavigatorState rootNavigator = Navigator.of(navigator.context, rootNavigator: true); rootNavigator.pop(); }
if (controller.isAnimating) { controller.animateBack( 0.0, duration: _kDroppedSheetDragAnimationDuration, curve: animationCurve, ); } }
if (controller.isAnimating) { // Keep the userGestureInProgress in true state so we don't change the // curve of the page transition mid-flight since CupertinoPageTransition // depends on userGestureInProgress. // late AnimationStatusListener animationStatusCallback; void animationStatusCallback(AnimationStatus status) { navigator.didStopUserGesture(); controller.removeStatusListener(animationStatusCallback); }
controller.addStatusListener(animationStatusCallback); } else { navigator.didStopUserGesture(); } }}44 unmodified lines45464748495051288 unmodified lines34034134234334434534634734834935099 unmodified lines4504514524534544554564574584594604614624632 unmodified lines46646746846947047147247347447547647747847928 unmodified lines5085095105115125135145155165175185195205215225235245255266 unmodified lines5335345355365375385395405415425435445455465475487 unmodified lines55655755855956056156256344 unmodified lines////// See also:////// * <https://developer.apple.com/ios/human-interface-guidelines/controls/sliders/>class CupertinoSlider extends StatefulWidget {/// Creates an iOS-style slider.///288 unmodified lines_trackColor = trackColor,_onChanged = onChanged,_textDirection = textDirection,super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth, height: _kSliderHeight)) {_drag = HorizontalDragGestureRecognizer()..onStart = _handleDragStart..onUpdate = _handleDragUpdate..onEnd = _handleDragEnd;_position = AnimationController(value: value,duration: _kDiscreteTransitionDuration,99 unmodified linesdouble get _trackLeft => _kPadding;double get _trackRight => size.width - _kPadding;double get _thumbCenter {final double visualPosition;switch (textDirection) {case TextDirection.rtl:visualPosition = 1.0 - _value;case TextDirection.ltr:visualPosition = _value;}return lerpDouble(_trackLeft + CupertinoThumbPainter.radius, _trackRight - CupertinoThumbPainter.radius, visualPosition)!;}bool get isInteractive => onChanged != null;2 unmodified linesvoid _handleDragUpdate(DragUpdateDetails details) {if (isInteractive) {final double extent = math.max(_kPadding, size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius));final double valueDelta = details.primaryDelta! / extent;switch (textDirection) {case TextDirection.rtl:_currentDragValue -= valueDelta;case TextDirection.ltr:_currentDragValue += valueDelta;}onChanged!(_discretizedCurrentDragValue);}}28 unmodified lines@overridevoid paint(PaintingContext context, Offset offset) {final double visualPosition;final Color leftColor;final Color rightColor;switch (textDirection) {case TextDirection.rtl:visualPosition = 1.0 - _position.value;leftColor = _activeColor;rightColor = trackColor;case TextDirection.ltr:visualPosition = _position.value;leftColor = trackColor;rightColor = _activeColor;}final double trackCenter = offset.dy + size.height / 2.0;final double trackLeft = offset.dx + _trackLeft;6 unmodified linesif (visualPosition > 0.0) {final Paint paint = Paint()..color = rightColor;canvas.drawRRect(RRect.fromLTRBXY(trackLeft, trackTop, trackActive, trackBottom, 1.0, 1.0), paint);}if (visualPosition < 1.0) {final Paint paint = Paint()..color = leftColor;canvas.drawRRect(RRect.fromLTRBXY(trackActive, trackTop, trackRight, trackBottom, 1.0, 1.0), paint);}final Offset thumbCenter = Offset(trackActive, trackCenter);CupertinoThumbPainter(color: thumbColor).paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius));}@override7 unmodified linesconfig.onIncrease = _increaseAction;config.onDecrease = _decreaseAction;config.value = '${(value * 100).round()}%';config.increasedValue = '${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%';config.decreasedValue = '${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%';}}44 unmodified lines45464748495051288 unmodified lines34034134234334434534634734834935035135235335435535699 unmodified lines4564574584594604614624634644654664674684694702 unmodified lines47347447547647747847948048148248348448548648728 unmodified lines5165175185195205215225235245256 unmodified lines5325335345355365375385395405415425435445455465475485495505515525535545557 unmodified lines56356456556656756856957057157244 unmodified lines////// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/sliders/>class CupertinoSlider extends StatefulWidget {/// Creates an iOS-style slider.///288 unmodified lines_trackColor = trackColor,_onChanged = onChanged,_textDirection = textDirection,super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth,height: _kSliderHeight,),) {_drag =HorizontalDragGestureRecognizer()..onStart = _handleDragStart..onUpdate = _handleDragUpdate..onEnd = _handleDragEnd;_position = AnimationController(value: value,duration: _kDiscreteTransitionDuration,99 unmodified linesdouble get _trackLeft => _kPadding;double get _trackRight => size.width - _kPadding;double get _thumbCenter {final double visualPosition = switch (textDirection) {TextDirection.rtl => 1.0 - _value,TextDirection.ltr => _value,};return lerpDouble(_trackLeft + CupertinoThumbPainter.radius,_trackRight - CupertinoThumbPainter.radius,visualPosition,)!;}bool get isInteractive => onChanged != null;2 unmodified linesvoid _handleDragUpdate(DragUpdateDetails details) {if (isInteractive) {final double extent = math.max(_kPadding,size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius),);final double valueDelta = details.primaryDelta! / extent;_currentDragValue += switch (textDirection) {TextDirection.rtl => -valueDelta,TextDirection.ltr => valueDelta,};onChanged!(_discretizedCurrentDragValue);}}28 unmodified lines@overridevoid paint(PaintingContext context, Offset offset) {final (double visualPosition, Color leftColor, Color rightColor) = switch (textDirection) {TextDirection.rtl => (1.0 - _position.value, _activeColor, trackColor),TextDirection.ltr => (_position.value, trackColor, _activeColor),};final double trackCenter = offset.dy + size.height / 2.0;final double trackLeft = offset.dx + _trackLeft;6 unmodified linesif (visualPosition > 0.0) {final Paint paint = Paint()..color = rightColor;canvas.drawRRect(RRect.fromLTRBXY(trackLeft, trackTop, trackActive, trackBottom, 1.0, 1.0),paint,);}if (visualPosition < 1.0) {final Paint paint = Paint()..color = leftColor;canvas.drawRRect(RRect.fromLTRBXY(trackActive, trackTop, trackRight, trackBottom, 1.0, 1.0),paint,);}final Offset thumbCenter = Offset(trackActive, trackCenter);CupertinoThumbPainter(color: thumbColor,).paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius));}@override7 unmodified linesconfig.onIncrease = _increaseAction;config.onDecrease = _decreaseAction;config.value = '${(value * 100).round()}%';config.increasedValue ='${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%';config.decreasedValue ='${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%';}}
1 unmodified line234567893 unmodified lines131415161718192021222324259 unmodified lines3536373839404142431 unmodified line454647484950512 unmodified lines545556575859606162636465666768697015 unmodified lines868788899091929394959697989910010110210310441 unmodified lines1461471481491501515 unmodified lines1571581591601611621631641651661671684 unmodified lines1731741751761771781791801811821833 unmodified lines1871881891901911921931941951961 unmodified line19819920020120220320437 unmodified lines24224324424524624724847 unmodified lines29629729829930030130213 unmodified lines3163173183193203213223233243259 unmodified lines33533633733833934051 unmodified lines39239339439539639710 unmodified lines40840941041141241341441541641741841942042142242342442542642742811 unmodified lines44044144244344444544629 unmodified lines4764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125132 unmodified lines5165175185195205215225235245255265272 unmodified lines5305315325335345355366 unmodified lines5435445455465475485494 unmodified lines5545555565575585595601 unmodified line5625635645655665672 unmodified lines57057157257357457557657757857958058158258321 unmodified lines60560660760860961061134 unmodified lines6466476486496506516526536546553 unmodified lines65966066166266366419 unmodified lines6846856866876886896906916926936946956966976986997007014 unmodified lines7067077087097107117127137147157167177187197207217227237242 unmodified lines7277287297307317324 unmodified lines73773873974074174274374474574674727 unmodified lines77577677777877978078178278378478578678778878979079146 unmodified lines8388398408418428436 unmodified lines85085185285385485585685762 unmodified lines9209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709714 unmodified lines97697797897998098198298310 unmodified lines99499599699799899910001001100210 unmodified lines1013101410151016101710183 unmodified lines102210231024102510261027102810291 unmodified line103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210534 unmodified lines1058105910601061106210631 unmodified line10651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110922 unmodified lines109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:math' as math;import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/physics.dart';3 unmodified linesimport 'colors.dart';// Extracted from https://developer.apple.com/design/resources/.// Minimum padding from edges of the segmented control to edges of// encompassing widget.const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(vertical: 2, horizontal: 3);// The corner radius of the thumb.const Radius _kThumbRadius = Radius.circular(6.93);// The amount of space by which to expand the thumb from the size of the currently// selected child.const EdgeInsets _kThumbInsets = EdgeInsets.symmetric(horizontal: 1);9 unmodified lines);// The amount of space by which to inset each separator.const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 6);const double _kSeparatorWidth = 1;const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth/2);// The minimum scale factor of the thumb, when being pressed on for a sufficient// amount of time.1 unmodified line// The minimum horizontal distance between the edges of the separator and the// closest child.const double _kSegmentMinPadding = 9.25;// The threshold value used in hasDraggedTooFar, for checking against the square// L2 distance from the location of the current drag pointer, to the closest2 unmodified lines// Both the mechanism and the value are speculated.const double _kTouchYDistanceThreshold = 50.0 * 50.0;// The corner radius of the segmented control.//// Inspected from iOS 13.2 simulator.const double _kCornerRadius = 8;// The minimum opacity of an unselected segment, when the user presses on the// segment and it starts to fadeout.//// Inspected from iOS 13.2 simulator.const double _kContentPressedMinOpacity = 0.2;// The spring animation used when the thumb changes its rect.final SpringSimulation _kThumbSpringAnimationSimulation = SpringSimulation(const SpringDescription(mass: 1, stiffness: 503.551, damping: 44.8799),15 unmodified linesrequired this.pressed,required this.highlighted,required this.isDragging,}) : super(key: key);final Widget child;final bool pressed;final bool highlighted;// Whether the thumb of the parent widget (CupertinoSlidingSegmentedControl)// is currently being dragged.final bool isDragging;bool get shouldFadeoutContent => pressed && !highlighted;bool get shouldScaleContent => pressed && highlighted && isDragging;@override_SegmentState<T> createState() => _SegmentState<T>();41 unmodified lines@overrideWidget build(BuildContext context) {return MetaData(// Expand the hitTest area of this widget.behavior: HitTestBehavior.opaque,5 unmodified linesduration: _kOpacityAnimationDuration,curve: Curves.ease,child: AnimatedDefaultTextStyle(style: DefaultTextStyle.of(context).style.merge(TextStyle(fontWeight: widget.highlighted ? FontWeight.w500 : FontWeight.normal)),duration: _kHighlightAnimationDuration,curve: Curves.ease,child: ScaleTransition(scale: highlightPressScaleAnimation,child: widget.child,),4 unmodified lines// the same and will always be greater than equal to that of the// visible child (at index 0), to keep the size of the entire// SegmentedControl widget consistent throughout the animation.Offstage(child: DefaultTextStyle.merge(style: const TextStyle(fontWeight: FontWeight.w500),child: widget.child,),),],),3 unmodified lines// Fadeout the separator when either adjacent segment is highlighted.class _SegmentSeparator extends StatefulWidget {const _SegmentSeparator({required ValueKey<int> key,required this.highlighted,}) : super(key: key);final bool highlighted;1 unmodified line_SegmentSeparatorState createState() => _SegmentSeparatorState();}class _SegmentSeparatorState extends State<_SegmentSeparator> with TickerProviderStateMixin<_SegmentSeparator> {late final AnimationController separatorOpacityController;@override37 unmodified linespadding: _kSeparatorInset,child: DecoratedBox(decoration: BoxDecoration(color: _kSeparatorColor.withOpacity(_kSeparatorColor.opacity * separatorOpacityController.value),borderRadius: const BorderRadius.all(_kSeparatorRadius),),child: child,47 unmodified lines/// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/segmented-controls/>class CupertinoSlidingSegmentedControl<T> extends StatefulWidget {/// Creates an iOS-style segmented control bar.////// The [children] argument must be an ordered [Map] such as a13 unmodified linessuper.key,required this.children,required this.onValueChanged,this.groupValue,this.thumbColor = _kThumbColor,this.padding = _kHorizontalItemPadding,this.backgroundColor = CupertinoColors.tertiarySystemFill,}) : assert(children.length >= 2),assert(groupValue == null || children.keys.contains(groupValue),9 unmodified lines/// The map must have more than one entry.final Map<T, Widget> children;/// The identifier of the widget that is currently selected.////// This must be one of the keys in the [Map] of [children].51 unmodified lines/// will not be painted if null is specified.final Color backgroundColor;/// The color used to paint the interior of the thumb that appears behind the/// currently selected item.///10 unmodified linesState<CupertinoSlidingSegmentedControl<T>> createState() => _SegmentedControlState<T>();}class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T>>with TickerProviderStateMixin<CupertinoSlidingSegmentedControl<T>> {late final AnimationController thumbController = AnimationController(duration: _kSpringAnimationDuration, value: 0, vsync: this);Animatable<Rect?>? thumbAnimatable;late final AnimationController thumbScaleController = AnimationController(duration: _kSpringAnimationDuration, value: 0, vsync: this);late Animation<double> thumbScaleAnimation = thumbScaleController.drive(Tween<double>(begin: 1, end: _kMinThumbScale));final TapGestureRecognizer tap = TapGestureRecognizer();final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer();final LongPressGestureRecognizer longPress = LongPressGestureRecognizer();@overridevoid initState() {super.initState();// If the long press or horizontal drag recognizer gets accepted, we know for// sure the gesture is meant for the segmented control. Hand everything to// the drag gesture recognizer.11 unmodified linestap.onTapUp = onTapUp;// Empty callback to enable the long press recognizer.longPress.onLongPress = () { };highlighted = widget.groupValue;}29 unmodified lines// Otherwise the thumb can be dragged around in an ongoing drag gesture.bool? _startedOnSelectedSegment;// Whether an ongoing horizontal drag gesture that started on the thumb is// present. When true, defer/ignore changes to the `highlighted` variable// from other sources (except for semantics) until the gesture ends, preventing// them from interfering with the active drag gesture.bool get isThumbDragging => _startedOnSelectedSegment ?? false;// Converts local coordinate to segments. This method assumes each segment has// the same width.T segmentForXPosition(double dx) {final RenderBox renderBox = context.findRenderObject()! as RenderBox;final int numOfChildren = widget.children.length;assert(renderBox.hasSize);assert(numOfChildren >= 2);int index = (dx ~/ (renderBox.size.width / numOfChildren)).clamp(0, numOfChildren - 1);switch (Directionality.of(context)) {case TextDirection.ltr:break;case TextDirection.rtl:index = numOfChildren - 1 - index;}return widget.children.keys.elementAt(index);}bool _hasDraggedTooFar(DragUpdateDetails details) {final RenderBox renderBox = context.findRenderObject()! as RenderBox;assert(renderBox.hasSize);final Size size = renderBox.size;final Offset offCenter = details.localPosition - Offset(size.width/2, size.height/2);final double l2 = math.pow(math.max(0.0, offCenter.dx.abs() - size.width/2), 2)+ math.pow(math.max(0.0, offCenter.dy.abs() - size.height/2), 2) as double;return l2 > _kTouchYDistanceThreshold;}2 unmodified lines// This animation must be synced with the segment scale animation (see the// _Segment widget) to make the overall animation look natural when the thumb// is not sliding.void _playThumbScaleAnimation({ required bool isExpanding }) {thumbScaleAnimation = thumbScaleController.drive(Tween<double>(begin: thumbScaleAnimation.value,end: isExpanding ? 1 : _kMinThumbScale,),);thumbScaleController.animateWith(_kThumbSpringAnimationSimulation);}2 unmodified linesif (highlighted == newValue) {return;}setState(() { highlighted = newValue; });// Additionally, start the thumb animation if the highlighted segment// changes. If the thumbController is already running, the render object's// paint method will create a new tween to drive the animation with.6 unmodified linesvoid onPressedChangedByGesture(T? newValue) {if (pressed != newValue) {setState(() { pressed = newValue; });}}4 unmodified lines}final T segment = segmentForXPosition(details.localPosition.dx);onPressedChangedByGesture(null);if (segment != widget.groupValue) {widget.onValueChanged(segment);}}1 unmodified linevoid onDown(DragDownDetails details) {final T touchDownSegment = segmentForXPosition(details.localPosition.dx);_startedOnSelectedSegment = touchDownSegment == highlighted;onPressedChangedByGesture(touchDownSegment);if (isThumbDragging) {2 unmodified lines}void onUpdate(DragUpdateDetails details) {if (isThumbDragging) {final T segment = segmentForXPosition(details.localPosition.dx);onPressedChangedByGesture(segment);onHighlightChangedByGesture(segment);} else {final T? segment = _hasDraggedTooFar(details)? null: segmentForXPosition(details.localPosition.dx);onPressedChangedByGesture(segment);}}21 unmodified linesif (isThumbDragging) {_playThumbScaleAnimation(isExpanding: true);}onPressedChangedByGesture(null);_startedOnSelectedSegment = null;}34 unmodified lines);}children.add(Semantics(button: true,onTap: () { widget.onValueChanged(entry.key); },inMutuallyExclusiveGroup: true,selected: widget.groupValue == entry.key,child: MouseRegion(3 unmodified lineshighlighted: isHighlighted,pressed: pressed == entry.key,isDragging: isThumbDragging,child: entry.value,),),19 unmodified linesreturn UnconstrainedBox(constrainedAxis: Axis.horizontal,child: Container(padding: widget.padding.resolve(Directionality.of(context)),decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(_kCornerRadius)),color: CupertinoDynamicColor.resolve(widget.backgroundColor, context),),child: AnimatedBuilder(animation: thumbScaleAnimation,builder: (BuildContext context, Widget? child) {return _SegmentedControlRenderWidget<T>(highlightedIndex: highlightedIndex,thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor, context),thumbScale: thumbScaleAnimation.value,state: this,children: children,);4 unmodified lines}}class _SegmentedControlRenderWidget<T> extends MultiChildRenderObjectWidget {const _SegmentedControlRenderWidget({super.key,super.children,required this.highlightedIndex,required this.thumbColor,required this.thumbScale,required this.state,});final int? highlightedIndex;final Color thumbColor;final double thumbScale;final _SegmentedControlState<T> state;@override2 unmodified lineshighlightedIndex: highlightedIndex,thumbColor: thumbColor,thumbScale: thumbScale,state: state,);}4 unmodified linesrenderObject..thumbColor = thumbColor..thumbScale = thumbScale..highlightedIndex = highlightedIndex;}}class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData<RenderBox> { }// The behavior of a UISegmentedControl as observed on iOS 13.1://27 unmodified lines// region (either outside of the segmented control's vicinity or to a// different segment). The reverse animation has the same duration and timing// function.class _RenderSegmentedControl<T> extends RenderBoxwith ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {_RenderSegmentedControl({required int? highlightedIndex,required Color thumbColor,required double thumbScale,required this.state,}) : _highlightedIndex = highlightedIndex,_thumbColor = thumbColor,_thumbScale = thumbScale;final _SegmentedControlState<T> state;46 unmodified linesmarkNeedsPaint();}@overridevoid handleEvent(PointerEvent event, BoxHitTestEntry entry) {assert(debugHandleEvent(event, entry));6 unmodified lines}// Intrinsic Dimensionsdouble get totalSeparatorWidth => (_kSeparatorInset.horizontal + _kSeparatorWidth) * (childCount ~/ 2);RenderBox? nonSeparatorChildAfter(RenderBox child) {final RenderBox? nextChild = childAfter(child);62 unmodified lines}}Size _calculateChildSize(BoxConstraints constraints) {final int childCount = this.childCount ~/ 2 + 1;double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount;double maxHeight = _kMinSegmentedControlHeight;RenderBox? child = firstChild;while (child != null) {childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding);child = nonSeparatorChildAfter(child);}childWidth = math.min(childWidth,(constraints.maxWidth - totalSeparatorWidth) / childCount,);child = firstChild;while (child != null) {final double boxHeight = child.getMaxIntrinsicHeight(childWidth);maxHeight = math.max(maxHeight, boxHeight);child = nonSeparatorChildAfter(child);}return Size(childWidth, maxHeight);}Size _computeOverallSizeFromChildSize(Size childSize, BoxConstraints constraints) {final int childCount = this.childCount ~/ 2 + 1;return constraints.constrain(Size(childSize.width * childCount + totalSeparatorWidth, childSize.height));}@overrideSize computeDryLayout(BoxConstraints constraints) {final Size childSize = _calculateChildSize(constraints);return _computeOverallSizeFromChildSize(childSize, constraints);}@overridevoid performLayout() {final BoxConstraints constraints = this.constraints;final Size childSize = _calculateChildSize(constraints);final BoxConstraints childConstraints = BoxConstraints.tight(childSize);final BoxConstraints separatorConstraints = childConstraints.heightConstraints();RenderBox? child = firstChild;int index = 0;double start = 0;while (child != null) {child.layout(index.isEven ? childConstraints : separatorConstraints, parentUsesSize: true);final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;final Offset childOffset = Offset(start, 0);childParentData.offset = childOffset;start += child.size.width;4 unmodified lineschild = childAfter(child);index += 1;}size = _computeOverallSizeFromChildSize(childSize, constraints);}// This method is used to convert the original unscaled thumb rect painted in10 unmodified linesreturn null;}final Offset firstChildOffset = (children.first.parentData! as _SegmentedControlContainerBoxParentData).offset;final double leftMost = firstChildOffset.dx;final double rightMost = (children.last.parentData! as _SegmentedControlContainerBoxParentData).offset.dx + children.last.size.width;assert(rightMost > leftMost);// Ignore the horizontal position and the height of `thumbRect`, and10 unmodified linesvoid paint(PaintingContext context, Offset offset) {final List<RenderBox> children = getChildrenAsList();for (int index = 1; index < childCount; index += 2) {_paintSeparator(context, offset, children[index]);}3 unmodified linesif (highlightedChildIndex != null) {final RenderBox selectedChild = children[highlightedChildIndex * 2];final _SegmentedControlContainerBoxParentData childParentData = selectedChild.parentData! as _SegmentedControlContainerBoxParentData;final Rect newThumbRect = _kThumbInsets.inflateRect(childParentData.offset & selectedChild.size);// Update thumb animation's tween, in case the end rect changed (e.g., a// new segment is added during the animation).1 unmodified linefinal Animatable<Rect?>? thumbTween = state.thumbAnimatable;if (thumbTween == null) {// This is the first frame of the animation.final Rect startingRect = moveThumbRectInBound(currentThumbRect, children) ?? newThumbRect;state.thumbAnimatable = RectTween(begin: startingRect, end: newThumbRect);} else if (newThumbRect != thumbTween.transform(1)) {// The thumbTween of the running sliding animation needs updating,// without restarting the animation.final Rect startingRect = moveThumbRectInBound(currentThumbRect, children) ?? newThumbRect;state.thumbAnimatable = RectTween(begin: startingRect, end: newThumbRect).chain(CurveTween(curve: Interval(state.thumbController.value, 1)));}} else {state.thumbAnimatable = null;}final Rect unscaledThumbRect = state.thumbAnimatable?.evaluate(state.thumbController) ?? newThumbRect;currentThumbRect = unscaledThumbRect;final Rect thumbRect = Rect.fromCenter(center: unscaledThumbRect.center,width: unscaledThumbRect.width * thumbScale,height: unscaledThumbRect.height * thumbScale,);4 unmodified lines}for (int index = 0; index < children.length; index += 2) {_paintChild(context, offset, children[index]);}}1 unmodified line// Paint the separator to the right of the given child.final Paint separatorPaint = Paint();void _paintSeparator(PaintingContext context, Offset offset, RenderBox child) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;context.paintChild(child, offset + childParentData.offset);}void _paintChild(PaintingContext context, Offset offset, RenderBox child) {final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;context.paintChild(child, childParentData.offset + offset);}void _paintThumb(PaintingContext context, Offset offset, Rect thumbRect) {// Colors extracted from https://developer.apple.com/design/resources/.const List<BoxShadow> thumbShadow = <BoxShadow> [BoxShadow(color: Color(0x1F000000),offset: Offset(0, 3),blurRadius: 8,),BoxShadow(color: Color(0x0A000000),offset: Offset(0, 3),blurRadius: 1,),];final RRect thumbRRect = RRect.fromRectAndRadius(thumbRect.shift(offset), _kThumbRadius);2 unmodified linescontext.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint());}context.canvas.drawRRect(thumbRRect.inflate(0.5),Paint()..color = const Color(0x0A000000),);context.canvas.drawRRect(thumbRRect,Paint()..color = thumbColor,);}@overridebool hitTestChildren(BoxHitTestResult result, { required Offset position }) {RenderBox? child = lastChild;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;if ((childParentData.offset & child.size).contains(position)) {return result.addWithPaintOffset(offset: childParentData.offset,1 unmodified line2345678910111213143 unmodified lines18192021222324252627282930313233349 unmodified lines4445464748495051521 unmodified line545556575859602 unmodified lines63646566676869707172737475767778798081828384858615 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312441 unmodified lines1661671681691701711721731741751761775 unmodified lines1831841851861871881891901911921931941951961971981994 unmodified lines2042052062072082092102112123 unmodified lines2162172182192202212222231 unmodified line22522622722822923023123237 unmodified lines27027127227327427527627727847 unmodified lines32632732832933033133213 unmodified lines3463473483493503513523533543553563579 unmodified lines36736836937037137237337437537637737837938038138238338438538651 unmodified lines43843944044144244344444544644744844945045145245345445545645745810 unmodified lines46947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050111 unmodified lines51351451551651751851929 unmodified lines5495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935942 unmodified lines5975985996006016026036046052 unmodified lines6086096106116126136146156166176 unmodified lines6246256266276286296306316324 unmodified lines6376386396406416426431 unmodified line6456466476486496506516526536542 unmodified lines65765865966066166266366466566666766866967067167267367467567667767867921 unmodified lines70170270370470570634 unmodified lines7417427437447457467477487497507517527537547557567577587597607617627633 unmodified lines76776876977077177277377419 unmodified lines7947957967977987998008018028038048058068078088098108118128138148158164 unmodified lines8218228238248258268278288298308318328338348358368378388398408412 unmodified lines8448458468478488498504 unmodified lines85585685785885986086186286386486586686786827 unmodified lines89689789889990090190290390490590690790890991091191291391491546 unmodified lines9629639649659669679689699709719729739749759769776 unmodified lines98498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101762 unmodified lines10801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912004 unmodified lines120512061207120812091210121110 unmodified lines12221223122412251226122712281229123012311232123310 unmodified lines1244124512461247124812491250125112523 unmodified lines125612571258125912601261126212631264126512661 unmodified line1268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113124 unmodified lines1317131813191320132113221323132413251 unmodified line13271328132913301331133213331334133513361337133813391340134113421343134413451346134713482 unmodified lines135113521353135413551356135713581359136013611362136313641365136613671 unmodified line// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file./// @docImport 'dart:collection';library;import 'dart:math' as math;import 'dart:math';import 'package:collection/collection.dart';import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/physics.dart';3 unmodified linesimport 'colors.dart';// Extracted from https://developer.apple.com/design/resources/.// Default values have been updated to match iOS 17 figma file: https://www.figma.com/community/file/1248375255495415511.// Minimum padding from edges of the segmented control to edges of// encompassing widget.const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(vertical: 2, horizontal: 3);// The corner radius of the segmented control.const Radius _kCornerRadius = Radius.circular(9);// The corner radius of the thumb.const Radius _kThumbRadius = Radius.circular(7);// The amount of space by which to expand the thumb from the size of the currently// selected child.const EdgeInsets _kThumbInsets = EdgeInsets.symmetric(horizontal: 1);9 unmodified lines);// The amount of space by which to inset each separator.const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 5);const double _kSeparatorWidth = 1;const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth / 2);// The minimum scale factor of the thumb, when being pressed on for a sufficient// amount of time.1 unmodified line// The minimum horizontal distance between the edges of the separator and the// closest child.const double _kSegmentMinPadding = 10;// The threshold value used in hasDraggedTooFar, for checking against the square// L2 distance from the location of the current drag pointer, to the closest2 unmodified lines// Both the mechanism and the value are speculated.const double _kTouchYDistanceThreshold = 50.0 * 50.0;// The minimum opacity of an unselected segment, when the user presses on the// segment and it starts to fadeout.//// Inspected from iOS 17.5 simulator.const double _kContentPressedMinOpacity = 0.2;// Inspected from iOS 17.5 simulator.const double _kFontSize = 13.0;// Inspected from iOS 17.5 simulator.const FontWeight _kFontWeight = FontWeight.w500;// Inspected from iOS 17.5 simulator.const FontWeight _kHighlightedFontWeight = FontWeight.w600;// Inspected from iOS 17.5 simulatorconst Color _kDisabledContentColor = Color.fromARGB(115, 122, 122, 122);// The spring animation used when the thumb changes its rect.final SpringSimulation _kThumbSpringAnimationSimulation = SpringSimulation(const SpringDescription(mass: 1, stiffness: 503.551, damping: 44.8799),15 unmodified linesrequired this.pressed,required this.highlighted,required this.isDragging,required this.enabled,required this.segmentLocation,}) : super(key: key);final Widget child;final bool pressed;final bool highlighted;final bool enabled;final _SegmentLocation segmentLocation;// Whether the thumb of the parent widget (CupertinoSlidingSegmentedControl)// is currently being dragged.final bool isDragging;bool get shouldFadeoutContent => pressed && !highlighted && enabled;bool get shouldScaleContent => pressed && highlighted && isDragging && enabled;@override_SegmentState<T> createState() => _SegmentState<T>();41 unmodified lines@overrideWidget build(BuildContext context) {final Alignment scaleAlignment = switch (widget.segmentLocation) {_SegmentLocation.leftmost => Alignment.centerLeft,_SegmentLocation.rightmost => Alignment.centerRight,_SegmentLocation.inbetween => Alignment.center,};return MetaData(// Expand the hitTest area of this widget.behavior: HitTestBehavior.opaque,5 unmodified linesduration: _kOpacityAnimationDuration,curve: Curves.ease,child: AnimatedDefaultTextStyle(style: DefaultTextStyle.of(context).style.merge(TextStyle(fontWeight: widget.highlighted ? _kHighlightedFontWeight : _kFontWeight,fontSize: _kFontSize,color: widget.enabled ? null : _kDisabledContentColor,),),duration: _kHighlightAnimationDuration,curve: Curves.ease,child: ScaleTransition(alignment: scaleAlignment,scale: highlightPressScaleAnimation,child: widget.child,),4 unmodified lines// the same and will always be greater than equal to that of the// visible child (at index 0), to keep the size of the entire// SegmentedControl widget consistent throughout the animation.DefaultTextStyle.merge(style: const TextStyle(fontWeight: _kHighlightedFontWeight, fontSize: _kFontSize),child: widget.child,),],),3 unmodified lines// Fadeout the separator when either adjacent segment is highlighted.class _SegmentSeparator extends StatefulWidget {const _SegmentSeparator({required ValueKey<int> key, required this.highlighted}): super(key: key);final bool highlighted;1 unmodified line_SegmentSeparatorState createState() => _SegmentSeparatorState();}class _SegmentSeparatorState extends State<_SegmentSeparator>with TickerProviderStateMixin<_SegmentSeparator> {late final AnimationController separatorOpacityController;@override37 unmodified linespadding: _kSeparatorInset,child: DecoratedBox(decoration: BoxDecoration(color: _kSeparatorColor.withOpacity(_kSeparatorColor.opacity * separatorOpacityController.value,),borderRadius: const BorderRadius.all(_kSeparatorRadius),),child: child,47 unmodified lines/// See also:////// * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/segmented-controls/>class CupertinoSlidingSegmentedControl<T extends Object> extends StatefulWidget {/// Creates an iOS-style segmented control bar.////// The [children] argument must be an ordered [Map] such as a13 unmodified linessuper.key,required this.children,required this.onValueChanged,this.disabledChildren = const <Never>{},this.groupValue,this.thumbColor = _kThumbColor,this.padding = _kHorizontalItemPadding,this.backgroundColor = CupertinoColors.tertiarySystemFill,this.proportionalWidth = false,}) : assert(children.length >= 2),assert(groupValue == null || children.keys.contains(groupValue),9 unmodified lines/// The map must have more than one entry.final Map<T, Widget> children;/// The set of identifying keys that correspond to the segments that should be/// disabled.////// Disabled children cannot be selected by dragging, but they can be selected/// programmatically. For example, if the [groupValue] is set to a disabled/// segment, the segment is still selected but the segment content looks disabled.////// If an enabled segment is selected by dragging gesture and becomes disabled/// before dragging finishes, [onValueChanged] will be triggered when finger is/// released and the disabled segment is selected.////// By default, all segments are selectable.final Set<T> disabledChildren;/// The identifier of the widget that is currently selected.////// This must be one of the keys in the [Map] of [children].51 unmodified lines/// will not be painted if null is specified.final Color backgroundColor;/// Determine whether segments have proportional widths based on their content.////// If false, all segments will have the same width, determined by the longest/// segment. If true, each segment's width will be determined by its individual/// content.////// If the max width of parent constraints is smaller than the width that the/// segmented control needs, The segment widths will scale down proportionally/// to ensure the segment control fits within the boundaries; similarly, if/// the min width of parent constraints is larger, the segment width will scales/// up to meet the min width requirement.////// Defaults to false.final bool proportionalWidth;/// The color used to paint the interior of the thumb that appears behind the/// currently selected item.///10 unmodified linesState<CupertinoSlidingSegmentedControl<T>> createState() => _SegmentedControlState<T>();}class _SegmentedControlState<T extends Object> extends State<CupertinoSlidingSegmentedControl<T>>with TickerProviderStateMixin<CupertinoSlidingSegmentedControl<T>> {late final AnimationController thumbController = AnimationController(duration: _kSpringAnimationDuration,value: 0,vsync: this,);Animatable<Rect?>? thumbAnimatable;late final AnimationController thumbScaleController = AnimationController(duration: _kSpringAnimationDuration,value: 0,vsync: this,);late Animation<double> thumbScaleAnimation = thumbScaleController.drive(Tween<double>(begin: 1, end: _kMinThumbScale),);final TapGestureRecognizer tap = TapGestureRecognizer();final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer();final LongPressGestureRecognizer longPress = LongPressGestureRecognizer();final GlobalKey segmentedControlRenderWidgetKey = GlobalKey();@overridevoid initState() {super.initState();// If the long press or horizontal drag recognizer gets accepted, we know for// sure the gesture is meant for the segmented control. Hand everything to// the drag gesture recognizer.11 unmodified linestap.onTapUp = onTapUp;// Empty callback to enable the long press recognizer.longPress.onLongPress = () {};highlighted = widget.groupValue;}29 unmodified lines// Otherwise the thumb can be dragged around in an ongoing drag gesture.bool? _startedOnSelectedSegment;// Whether the current drag gesture started on a disabled segment. When this// flag is true, drag gestures will be ignored.bool _startedOnDisabledSegment = false;// Whether an ongoing horizontal drag gesture that started on the thumb is// present. When true, defer/ignore changes to the `highlighted` variable// from other sources (except for semantics) until the gesture ends, preventing// them from interfering with the active drag gesture.bool get isThumbDragging => (_startedOnSelectedSegment ?? false) && !_startedOnDisabledSegment;// Converts local coordinate to segments.T segmentForXPosition(double dx) {final BuildContext currentContext = segmentedControlRenderWidgetKey.currentContext!;final _RenderSegmentedControl<T> renderBox =currentContext.findRenderObject()! as _RenderSegmentedControl<T>;final int numOfChildren = widget.children.length;assert(renderBox.hasSize);assert(numOfChildren >= 2);int segmentIndex = renderBox.getClosestSegmentIndex(dx);switch (Directionality.of(context)) {case TextDirection.ltr:break;case TextDirection.rtl:segmentIndex = numOfChildren - 1 - segmentIndex;}return widget.children.keys.elementAt(segmentIndex);}bool _hasDraggedTooFar(DragUpdateDetails details) {final RenderBox renderBox = context.findRenderObject()! as RenderBox;assert(renderBox.hasSize);final Size size = renderBox.size;final Offset offCenter = details.localPosition - Offset(size.width / 2, size.height / 2);final double l2 =math.pow(math.max(0.0, offCenter.dx.abs() - size.width / 2), 2) +math.pow(math.max(0.0, offCenter.dy.abs() - size.height / 2), 2)as double;return l2 > _kTouchYDistanceThreshold;}2 unmodified lines// This animation must be synced with the segment scale animation (see the// _Segment widget) to make the overall animation look natural when the thumb// is not sliding.void _playThumbScaleAnimation({required bool isExpanding}) {thumbScaleAnimation = thumbScaleController.drive(Tween<double>(begin: thumbScaleAnimation.value, end: isExpanding ? 1 : _kMinThumbScale),);thumbScaleController.animateWith(_kThumbSpringAnimationSimulation);}2 unmodified linesif (highlighted == newValue) {return;}setState(() {highlighted = newValue;});// Additionally, start the thumb animation if the highlighted segment// changes. If the thumbController is already running, the render object's// paint method will create a new tween to drive the animation with.6 unmodified linesvoid onPressedChangedByGesture(T? newValue) {if (pressed != newValue) {setState(() {pressed = newValue;});}}4 unmodified lines}final T segment = segmentForXPosition(details.localPosition.dx);onPressedChangedByGesture(null);if (segment != widget.groupValue && !widget.disabledChildren.contains(segment)) {widget.onValueChanged(segment);}}1 unmodified linevoid onDown(DragDownDetails details) {final T touchDownSegment = segmentForXPosition(details.localPosition.dx);_startedOnSelectedSegment = touchDownSegment == highlighted;_startedOnDisabledSegment = widget.disabledChildren.contains(touchDownSegment);if (widget.disabledChildren.contains(touchDownSegment)) {return;}onPressedChangedByGesture(touchDownSegment);if (isThumbDragging) {2 unmodified lines}void onUpdate(DragUpdateDetails details) {// If drag gesture starts on disabled segment, no update needed.if (_startedOnDisabledSegment) {return;}// If drag gesture starts on enabled segment and dragging on disabled segment,// no update needed.final T touchDownSegment = segmentForXPosition(details.localPosition.dx);if (widget.disabledChildren.contains(touchDownSegment)) {return;}if (isThumbDragging) {onPressedChangedByGesture(touchDownSegment);onHighlightChangedByGesture(touchDownSegment);} else {final T? segment =_hasDraggedTooFar(details) ? null : segmentForXPosition(details.localPosition.dx);onPressedChangedByGesture(segment);}}21 unmodified linesif (isThumbDragging) {_playThumbScaleAnimation(isExpanding: true);}onPressedChangedByGesture(null);_startedOnSelectedSegment = null;}34 unmodified lines);}final TextDirection textDirection = Directionality.of(context);final _SegmentLocation segmentLocation = switch (textDirection) {TextDirection.ltr when index == 0 => _SegmentLocation.leftmost,TextDirection.ltr when index == widget.children.length - 1 => _SegmentLocation.rightmost,TextDirection.rtl when index == widget.children.length - 1 => _SegmentLocation.leftmost,TextDirection.rtl when index == 0 => _SegmentLocation.rightmost,TextDirection.ltr || TextDirection.rtl => _SegmentLocation.inbetween,};children.add(Semantics(button: true,onTap: () {if (widget.disabledChildren.contains(entry.key)) {return;}widget.onValueChanged(entry.key);},inMutuallyExclusiveGroup: true,selected: widget.groupValue == entry.key,child: MouseRegion(3 unmodified lineshighlighted: isHighlighted,pressed: pressed == entry.key,isDragging: isThumbDragging,enabled: !widget.disabledChildren.contains(entry.key),segmentLocation: segmentLocation,child: entry.value,),),19 unmodified linesreturn UnconstrainedBox(constrainedAxis: Axis.horizontal,child: Container(// Clip the thumb shadow if it is outside of the segmented control. This// behavior is eyeballed by the iOS 17.5 simulator.clipBehavior: Clip.antiAlias,padding: widget.padding.resolve(Directionality.of(context)),decoration: BoxDecoration(borderRadius: const BorderRadius.all(_kCornerRadius),color: CupertinoDynamicColor.resolve(widget.backgroundColor, context),),child: AnimatedBuilder(animation: thumbScaleAnimation,builder: (BuildContext context, Widget? child) {return _SegmentedControlRenderWidget<T>(key: segmentedControlRenderWidgetKey,highlightedIndex: highlightedIndex,thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor, context),thumbScale: thumbScaleAnimation.value,proportionalWidth: widget.proportionalWidth,state: this,children: children,);4 unmodified lines}}class _SegmentedControlRenderWidget<T extends Object> extends MultiChildRenderObjectWidget {const _SegmentedControlRenderWidget({super.key,super.children,required this.highlightedIndex,required this.thumbColor,required this.thumbScale,required this.proportionalWidth,required this.state,});final int? highlightedIndex;final Color thumbColor;final double thumbScale;final bool proportionalWidth;final _SegmentedControlState<T> state;@override2 unmodified lineshighlightedIndex: highlightedIndex,thumbColor: thumbColor,thumbScale: thumbScale,proportionalWidth: proportionalWidth,state: state,);}4 unmodified linesrenderObject..thumbColor = thumbColor..thumbScale = thumbScale..highlightedIndex = highlightedIndex..proportionalWidth = proportionalWidth;}}class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData<RenderBox> {}enum _SegmentLocation { leftmost, rightmost, inbetween }// The behavior of a UISegmentedControl as observed on iOS 13.1://27 unmodified lines// region (either outside of the segmented control's vicinity or to a// different segment). The reverse animation has the same duration and timing// function.class _RenderSegmentedControl<T extends Object> extends RenderBoxwithContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {_RenderSegmentedControl({required int? highlightedIndex,required Color thumbColor,required double thumbScale,required bool proportionalWidth,required this.state,}) : _highlightedIndex = highlightedIndex,_thumbColor = thumbColor,_thumbScale = thumbScale,_proportionalWidth = proportionalWidth;final _SegmentedControlState<T> state;46 unmodified linesmarkNeedsPaint();}bool get proportionalWidth => _proportionalWidth;bool _proportionalWidth;set proportionalWidth(bool value) {if (_proportionalWidth == value) {return;}_proportionalWidth = value;markNeedsLayout();}@overridevoid handleEvent(PointerEvent event, BoxHitTestEntry entry) {assert(debugHandleEvent(event, entry));6 unmodified lines}// Intrinsic Dimensionsdouble get separatorWidth => _kSeparatorInset.horizontal + _kSeparatorWidth;double get totalSeparatorWidth => separatorWidth * (childCount ~/ 2);int getClosestSegmentIndex(double dx) {int index = 0;RenderBox? child = firstChild;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final double clampX = clampDouble(dx,childParentData.offset.dx,child.size.width + childParentData.offset.dx,);if (dx <= clampX) {break;}index++;child = nonSeparatorChildAfter(child);}final int segmentCount = childCount ~/ 2 + 1;// When the thumb is dragging out of bounds, the return result must be// smaller than segment count.return min(index, segmentCount - 1);}RenderBox? nonSeparatorChildAfter(RenderBox child) {final RenderBox? nextChild = childAfter(child);62 unmodified lines}}double _getMaxChildWidth(BoxConstraints constraints) {final int childCount = this.childCount ~/ 2 + 1;double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount;RenderBox? child = firstChild;while (child != null) {childWidth = math.max(childWidth,child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding,);child = nonSeparatorChildAfter(child);}return math.min(childWidth, (constraints.maxWidth - totalSeparatorWidth) / childCount);}double _getMaxChildHeight(BoxConstraints constraints, double childWidth) {double maxHeight = _kMinSegmentedControlHeight;RenderBox? child = firstChild;while (child != null) {final double boxHeight = child.getMaxIntrinsicHeight(childWidth);maxHeight = math.max(maxHeight, boxHeight);child = nonSeparatorChildAfter(child);}return maxHeight;}List<double> _getChildWidths(BoxConstraints constraints) {if (!proportionalWidth) {final double maxChildWidth = _getMaxChildWidth(constraints);final int segmentCount = childCount ~/ 2 + 1;return List<double>.filled(segmentCount, maxChildWidth);}final List<double> segmentWidths = <double>[];RenderBox? child = firstChild;while (child != null) {final double childWidth =child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding;child = nonSeparatorChildAfter(child);segmentWidths.add(childWidth);}final double totalWidth = segmentWidths.sum;// If the sum of the children's width is larger than the allowed max width,// each segment width should scale down until the overall size can fit in// the parent constraints; similarly, if the sum of the children's width is// smaller than the allowed min width, each segment width should scale up// until the overall size can fit in the parent constraints.final double allowedMaxWidth = constraints.maxWidth - totalSeparatorWidth;final double allowedMinWidth = constraints.minWidth - totalSeparatorWidth;final double scale = clampDouble(totalWidth, allowedMinWidth, allowedMaxWidth) / totalWidth;if (scale != 1) {for (int i = 0; i < segmentWidths.length; i++) {segmentWidths[i] = segmentWidths[i] * scale;}}return segmentWidths;}Size _computeOverallSize(BoxConstraints constraints) {final double maxChildHeight = _getMaxChildHeight(constraints, constraints.maxWidth);return constraints.constrain(Size(_getChildWidths(constraints).sum + totalSeparatorWidth, maxChildHeight),);}@overridedouble? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {final List<double> segmentWidths = _getChildWidths(constraints);final double childHeight = _getMaxChildHeight(constraints, constraints.maxWidth);int index = 0;BaselineOffset baselineOffset = BaselineOffset.noBaseline;RenderBox? child = firstChild;while (child != null) {final BoxConstraints childConstraints = BoxConstraints.tight(Size(segmentWidths[index], childHeight),);baselineOffset = baselineOffset.minOf(BaselineOffset(child.getDryBaseline(childConstraints, baseline)),);child = nonSeparatorChildAfter(child);index++;}return baselineOffset.offset;}@overrideSize computeDryLayout(BoxConstraints constraints) {return _computeOverallSize(constraints);}@overridevoid performLayout() {final BoxConstraints constraints = this.constraints;final List<double> segmentWidths = _getChildWidths(constraints);final double childHeight = _getMaxChildHeight(constraints, double.infinity);final BoxConstraints separatorConstraints = BoxConstraints(minHeight: childHeight,maxHeight: childHeight,);RenderBox? child = firstChild;int index = 0;double start = 0;while (child != null) {final BoxConstraints childConstraints = BoxConstraints.tight(Size(segmentWidths[index ~/ 2], childHeight),);child.layout(index.isEven ? childConstraints : separatorConstraints, parentUsesSize: true);final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;final Offset childOffset = Offset(start, 0);childParentData.offset = childOffset;start += child.size.width;4 unmodified lineschild = childAfter(child);index += 1;}size = _computeOverallSize(constraints);}// This method is used to convert the original unscaled thumb rect painted in10 unmodified linesreturn null;}final Offset firstChildOffset =(children.first.parentData! as _SegmentedControlContainerBoxParentData).offset;final double leftMost = firstChildOffset.dx;final double rightMost =(children.last.parentData! as _SegmentedControlContainerBoxParentData).offset.dx +children.last.size.width;assert(rightMost > leftMost);// Ignore the horizontal position and the height of `thumbRect`, and10 unmodified linesvoid paint(PaintingContext context, Offset offset) {final List<RenderBox> children = getChildrenAsList();// Children contains both segment and separator and the order is segment ->// separator -> segment. So to paint separators, index should start from 1 and// the step should be 2.for (int index = 1; index < childCount; index += 2) {_paintSeparator(context, offset, children[index]);}3 unmodified linesif (highlightedChildIndex != null) {final RenderBox selectedChild = children[highlightedChildIndex * 2];final _SegmentedControlContainerBoxParentData childParentData =selectedChild.parentData! as _SegmentedControlContainerBoxParentData;final Rect newThumbRect = _kThumbInsets.inflateRect(childParentData.offset & selectedChild.size,);// Update thumb animation's tween, in case the end rect changed (e.g., a// new segment is added during the animation).1 unmodified linefinal Animatable<Rect?>? thumbTween = state.thumbAnimatable;if (thumbTween == null) {// This is the first frame of the animation.final Rect startingRect =moveThumbRectInBound(currentThumbRect, children) ?? newThumbRect;state.thumbAnimatable = RectTween(begin: startingRect, end: newThumbRect);} else if (newThumbRect != thumbTween.transform(1)) {// The thumbTween of the running sliding animation needs updating,// without restarting the animation.final Rect startingRect =moveThumbRectInBound(currentThumbRect, children) ?? newThumbRect;state.thumbAnimatable = RectTween(begin: startingRect,end: newThumbRect,).chain(CurveTween(curve: Interval(state.thumbController.value, 1)));}} else {state.thumbAnimatable = null;}final Rect unscaledThumbRect =state.thumbAnimatable?.evaluate(state.thumbController) ?? newThumbRect;currentThumbRect = unscaledThumbRect;final _SegmentLocation childLocation;if (highlightedChildIndex == 0) {childLocation = _SegmentLocation.leftmost;} else if (highlightedChildIndex == children.length ~/ 2) {childLocation = _SegmentLocation.rightmost;} else {childLocation = _SegmentLocation.inbetween;}final double delta = switch (childLocation) {_SegmentLocation.leftmost => unscaledThumbRect.width - unscaledThumbRect.width * thumbScale,_SegmentLocation.rightmost =>unscaledThumbRect.width * thumbScale - unscaledThumbRect.width,_SegmentLocation.inbetween => 0,};final Rect thumbRect = Rect.fromCenter(center: unscaledThumbRect.center - Offset(delta / 2, 0),width: unscaledThumbRect.width * thumbScale,height: unscaledThumbRect.height * thumbScale,);4 unmodified lines}for (int index = 0; index < children.length; index += 2) {// Children contains both segment and separator and the order is segment ->// separator -> segment. So to paint separators, index should start from 0 and// the step should be 2._paintChild(context, offset, children[index]);}}1 unmodified line// Paint the separator to the right of the given child.final Paint separatorPaint = Paint();void _paintSeparator(PaintingContext context, Offset offset, RenderBox child) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;context.paintChild(child, offset + childParentData.offset);}void _paintChild(PaintingContext context, Offset offset, RenderBox child) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;context.paintChild(child, childParentData.offset + offset);}void _paintThumb(PaintingContext context, Offset offset, Rect thumbRect) {// Colors extracted from https://developer.apple.com/design/resources/.const List<BoxShadow> thumbShadow = <BoxShadow>[BoxShadow(color: Color(0x1F000000), offset: Offset(0, 3), blurRadius: 8),BoxShadow(color: Color(0x0A000000), offset: Offset(0, 3), blurRadius: 1),];final RRect thumbRRect = RRect.fromRectAndRadius(thumbRect.shift(offset), _kThumbRadius);2 unmodified linescontext.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint());}context.canvas.drawRRect(thumbRRect.inflate(0.5), Paint()..color = const Color(0x0A000000));context.canvas.drawRRect(thumbRRect, Paint()..color = thumbColor);}@overridebool hitTestChildren(BoxHitTestResult result, {required Offset position}) {RenderBox? child = lastChild;while (child != null) {final _SegmentedControlContainerBoxParentData childParentData =child.parentData! as _SegmentedControlContainerBoxParentData;if ((childParentData.offset & child.size).contains(position)) {return result.addWithPaintOffset(offset: childParentData.offset,
flutter/packages/flutter/lib/fix_data/README.md+1-2
flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml+135-2
flutter/packages/flutter/lib/fix_data/fix_gestures.yaml+1-1
flutter/packages/flutter/lib/fix_data/fix_painting.yaml+46-1
flutter/packages/flutter/lib/fix_data/fix_rendering.yaml+3-3
flutter/packages/flutter/lib/fix_data/fix_services.yaml+15-1
flutter/packages/flutter/lib/fix_data/fix_template.yaml+1-1
flutter/packages/flutter/lib/src/animation/animation.dart+120-23
flutter/packages/flutter/lib/src/animation/animation_controller.dart+243-129
flutter/packages/flutter/lib/src/animation/animation_style.dart+17-19
flutter/packages/flutter/lib/src/animation/animations.dart+46-57
flutter/packages/flutter/lib/src/animation/curves.dart+176-73
flutter/packages/flutter/lib/src/animation/listener_helpers.dart+40-34
flutter/packages/flutter/lib/src/animation/tween.dart+26-20
flutter/packages/flutter/lib/src/animation/tween_sequence.dart+2-6
flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart+21-32
flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart+13-10
flutter/packages/flutter/lib/src/cupertino/app.dart+167-36
flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart+33-38
flutter/packages/flutter/lib/src/cupertino/button.dart+367-74
flutter/packages/flutter/lib/src/cupertino/checkbox.dart+311-73
flutter/packages/flutter/lib/src/cupertino/colors.dart+187-110
flutter/packages/flutter/lib/src/cupertino/constants.dart+77
flutter/packages/flutter/lib/src/cupertino/context_menu.dart+314-399
flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart+24-37
flutter/packages/flutter/lib/src/cupertino/date_picker.dart+785-449
flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart+20-18
flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart+17-37
flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart+18-24
flutter/packages/flutter/lib/src/cupertino/dialog.dart
flutter/packages/flutter/lib/src/cupertino/form_row.dart+8-18
flutter/packages/flutter/lib/src/cupertino/form_section.dart+60-42
flutter/packages/flutter/lib/src/cupertino/icons.dart
flutter/packages/flutter/lib/src/cupertino/interface_level.dart+5-6
flutter/packages/flutter/lib/src/cupertino/list_section.dart+100-67
flutter/packages/flutter/lib/src/cupertino/list_tile.dart+81-85
flutter/packages/flutter/lib/src/cupertino/localizations.dart+32-9
flutter/packages/flutter/lib/src/cupertino/magnifier.dart+115-65
flutter/packages/flutter/lib/src/cupertino/nav_bar.dart
flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart+94-58
flutter/packages/flutter/lib/src/cupertino/picker.dart+83-24
flutter/packages/flutter/lib/src/cupertino/radio.dart+265-58
flutter/packages/flutter/lib/src/cupertino/refresh.dart+60-37
flutter/packages/flutter/lib/src/cupertino/route.dart+511-318
flutter/packages/flutter/lib/src/cupertino/scrollbar.dart+31-23
flutter/packages/flutter/lib/src/cupertino/search_field.dart+127-44
flutter/packages/flutter/lib/src/cupertino/segmented_control.dart+115-60
flutter/packages/flutter/lib/src/cupertino/sheet.dartAdded+825
flutter/packages/flutter/lib/src/cupertino/slider.dart+48-39
flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart+370-120